问题
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