Iterate through the array from 0 to array.length and add the objects to a "hash" (read: javascript polymorphic object). Observe:
var objects = [...];
var ids = {};
for (var i = 0; i < objects.length; ++i) { ids[objects[i].id] = objects[i]; }
// Now empty the list and push the non-duplicated objects back into it
objects = [];
// Check hasOwnProperty in case prototypes have been changed
for (var id in ids) { if (ids.hasOwnProperty(id)) { objects.push(ids[id]); } }
ids
can only contain one object per id
, so only the last object with id
will remain in ids
. Thus you are guaranteed to only have on instance of id
in your array after this operation.
There may be better ways to clean up your array, but then there are almost certainly better ways to do whatever you're trying to do without having to clean up the array in the first place.