2

Could you let me know how do I remove duplicates from an Array in type script.

My array will look something like

a = [{a: 1, b: 2}, {a: 1, b: 2}, {c: 3, d: 4}]

I am looking to get

a = [{a: 1, b: 2}, {c: 3, d: 4}]

I used Set data strucure like below

a = Array.from(new Set(a))

but still no use. Please let me know how to remove duplicates from an array using single statement?

Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
user2753523
  • 473
  • 2
  • 8
  • 23
  • 2
    Not really a typescript question, this is a more general javasript question. Moreover, there are already [plenty of answers](https://stackoverflow.com/questions/2218999/remove-duplicates-from-an-array-of-objects-in-javascript). – CRice Dec 15 '17 at 21:30
  • 1
    Not TypeScript, not Angular.... – Ruan Mendes Dec 15 '17 at 21:32
  • 2
    The reason your code doesn't filter elements is because two similar objects are still considered different objects because they point to different objects. You need to write your own code that uses a custom comparator. You could use underscore, or use it as inspiration for your code http://underscorejs.org/#uniq – Ruan Mendes Dec 15 '17 at 21:33
  • 1
    Hint `{foo:3} !== {foo:3}`. – Jared Smith Dec 15 '17 at 21:39
  • 1
    @JaredSmith Didn't I already say that? – Ruan Mendes Dec 15 '17 at 21:42
  • @JuanMendes I probably either fired that off without refreshing the page, or I just missed it. Sorry! – Jared Smith Dec 16 '17 at 18:46

1 Answers1

5

Is not in a single statement but is short.

var a = [{a: 1, b: 2}, {a: 1, b: 2}, {c: 3, d: 4}];
a = a.filter((value, index, array) => 
     !array.filter((v, i) => JSON.stringify(value) == JSON.stringify(v) && i < index).length);

console.log(a);
Your question sees like this:

Delete duplicated elements in array of objects Javascript

But like in the comment will fails for:

var a = [{a: 1, b: 2}, {b: 2, a: 1}]; 

You need a custom compare for your case:

function isEqual(a, b){
  for(var i in a)
       if(a[i] != b[i])
          return false;
  for(var i in b)
       if(b[i] != a[i])
          return false;
  return true;
}

var a = [{a: 1, b: 2}, {b: 2, a: 1}, {c: 3, d: 4}];
a = a.filter((value, index, array) => 
     !array.filter((v, i) => isEqual(value, v) && i < index).length);

console.log(a);

You can compare ids or somenthing like this to identify equal object in this sample i just compare the properties.

Like @Juan Mendes said in comment:

The reason your code doesn't filter elements is because two similar objects are still considered different objects because they point to different objects. You need to write your own code that uses a custom comparator.

Ciro Spaciari
  • 630
  • 5
  • 10