Remove objects in array with duplicate properties
Let's say I got an array like this:
var arr1 = [ 1, 1, 'a', 'a' ];
And I want to remove duplicates, this snippet is awesome:
var deduped = arr1.filter(function (el, i, arr) {
return arr.indexOf(el) === i;
});
But I got this array, and I want to remove objects that has duplicate properties:
var obj1 = {
name: "John",
id: 1
};
var obj2 = {
name: "Moe",
id: 1
};
var obj3 = {
name: "Jane",
id: 2
};
var arr2 = [obj1, obj2, obj3];
How do I write a function to remove either one of (in this case) obj1
or obj2
since they have the same id
?
I do not want to remove both!
JsFiddle
Reference for code snippet
Thanks in advance.
Use Array#filter
with thisArg
thisArg
, Value to use asthis
when executing callback.
var obj1 = {
name: "John",
id: 1
};
var obj2 = {
name: "Moe",
id: 1
};
var obj3 = {
name: "Jane",
id: 'toString'
};
var arr2 = [obj1, obj2, obj3];
var filtered = arr2.filter(function(el) {
if (!this[el.id]) {
this[el.id] = true;
return true;
}
return false;
}, Object.create(null));
console.log(filtered);
We can add a step to map all object IDs before
var arr2 = [obj1, obj2, obj3];
var ids = arr2.map(function(obj){
return obj.id;
})
var deduped2 = arr2.filter(function (el, i, arr) {
return ids.indexOf(el.id) === i;
});
You could use a compact version of checking and assigning to a hash object.
var obj1 = { name: "John", id: 1 },
obj2 = { name: "Moe", id: 1 },
obj3 = { name: "Jane", id: 2 },
arr2 = [obj1, obj2, obj3],
filtered = arr2.filter(function(a) {
return !this[a.id] && (this[a.id] = true);
}, Object.create(null));
console.log(filtered);