Removing duplicates from JS array
4 answers
We could do it quite simply by just looping over it. For each element, assign its place in a new array corresponding to its identifier. Previous identifiers are overwritten, so only the last one is saved.
var items=[
{ id: 1, name: 'aa' },
{ id: 1, name: 'bb' },
{ id: 2, name: 'cc' },
{ id: 1, name: 'dd' }
], newItems = [];
for (var i =0;i<items.length;i++){
newItems[items[i].id - 1] = items[i];
}
alert(JSON.stringify(newItems));
+1
source to share
This should do what you want:
var items = [
{ id: 1, name: 'aa' },
{ id: 1, name: 'bb' },
{ id: 2, name: 'cc' },
{ id: 1, name: 'dd' }
];
function removeDupIds(items){
var result = [],
uniqIds = {},
i = 0,
l = items.length;
for(; i<l; i++){
uniqIds[items[i].id] = items[i].name;
}
for(var k in uniqIds){
result.push({id: k, name: uniqIds[k]});
}
return result;
}
console.log(removeDupIds(items));
0
source to share
Using underscore it would be simple
_.uniq(items.reverse(), function(i1, i2) { return i1.id === i2.id; }))
Usually _.uniq
removes the same elements, but we can pass it a second parameter that defines the function used to determine if two elements are considered the same.
Required items.reverse()
because the OP seems to want the last element to take precedence.
0
user663031
source
to share