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.

1

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

5 Comments

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.
ok, previous code works only for strings. i've update the answer for object level checks.
arr is your original array which is being filtered to remove duplicate entries.
Thanks! Works perfect. I accepted this as the correct awnser :)
glad it helps you. happy coding :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.