urbz urbz - 16 days ago 5
Javascript Question

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



Thanks in advance.

Answer

Use Array#filter with thisArg

thisArg, Value to use as this 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);