3

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?

6
  • 2
    Not really a typescript question, this is a more general javasript question. Moreover, there are already plenty of answers. Commented Dec 15, 2017 at 21:30
  • 1
    Not TypeScript, not Angular.... Commented Dec 15, 2017 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 underscorejs.org/#uniq Commented Dec 15, 2017 at 21:33
  • 1
    Hint {foo:3} !== {foo:3}. Commented Dec 15, 2017 at 21:39
  • 1
    @JaredSmith Didn't I already say that? Commented Dec 15, 2017 at 21:42

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Answers without explanation of what the problem was are not as useful
This code will fail if your array is the following: var a = [{a: 1, b: 2}, {b: 2, a: 1}]; Because JSON.stringify will create different string for the two similar objects above.
You are right i will edit with a more complete example
Upvoted after you addressed my issues :)
Thanks i will try create better answers in the future

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.