Remove objects with a duplicate property from a javascript array

倖福魔咒の 提交于 2019-12-23 02:26:37

问题


I have a javascript array that contains several objects, each object having this format:

{'hits':21, 'date':2011-01-11, 'business_id':233}

I am using a sorting function to sort the array objects:

    my_array.sort(function(a, b){
        return b.hits-a.hits;
    });

This sorting results in having some adjacent objects with the same 'business_id'. I would like to remove the ones with duplicate 'business_id's to keep only the one of the duplicates having the newest date value.

How do I remove the objects from the array that have duplicate 'business_id', keeping the one with the newest 'date' value? Can I do it in the sort function, or with some filter function?


回答1:


If you use a master object, mapping business_id to objects, it'd be a lot simpler. This way, every time you add one of your objects to the master, you'd check to see if it was already defined. Then, you'd compare dates to see if you want to replace it.



来源:https://stackoverflow.com/questions/5062546/remove-objects-with-a-duplicate-property-from-a-javascript-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!