1

I need to remove all duplicate objects from my array. I know I can do it by using filter or reduce, but I want to use set instead since (if it works) it should be the shortes and cleanest option.

origionalArray

[{type: "A", label: "A", department: "C"},
{type: "B", label: "B", department: "C"},
{type: "B", label: "B", department: "C"}]

Expected output:

[{type: "A", label: "A", department: "C"},
{type: "B", label: "B", department: "C"}]

I tried:

distinctArray = new Set(origionalArray);

But it returns origionalArray. So my guess is it compares the objects by reference. In java i would override the equals method. But as far as I can find it online this can't be done in TS.

Any ideas how I can get this done? Thank you for your help and time.

SWeko
  • 28,824
  • 9
  • 68
  • 102
Niels Ferguson
  • 252
  • 1
  • 10

1 Answers1

1

You can remove duplicate from array in TS by using this.

const expected = new Set();
const unique = arr.filter(item => !expected.has(JSON.stringify(item)) ? expected.add(JSON.stringify(item)) : false);
Naseer
  • 174
  • 1
  • 8
  • I tried this, but it gives me the following error: ''TS2568: Type 'Set' is not an array type. Use compiler option '--downlevelIteration' to allow iterating of iterators.'' Adding **"downlevelIteration": true** to my tsconfig does not solve the problem. So I tried to use **Array.from(new Set(origionalArray)**. Then the error disapears, but I still get the origionalArray instead of the reduced Array. – Niels Ferguson Dec 11 '19 at 10:06
  • ok, previous code works only for strings. i've update the answer for object level checks. – Naseer Dec 11 '19 at 10:23
  • arr is your original array which is being filtered to remove duplicate entries. – Naseer Dec 11 '19 at 10:25
  • Thanks! Works perfect. I accepted this as the correct awnser :) – Niels Ferguson Dec 11 '19 at 10:35
  • glad it helps you. happy coding :) – Naseer Dec 11 '19 at 10:37