Use array filters to remove duplicates in an array.
We have seen how we could use sets or an intermediate object in a loop to eliminate duplicates within array.There always is a better way of doing things.
Why not use filter to make the code more readable and not use set
at the same time :) ?
Consider this array -
|
|
The below code will create a unique array.
|
|
Why will this work? Well, because nums.indexOf(num)
always returns the first index of a particular element.
So - for the element 1
, the function will always return 0
. The condition is satisfied for 1
in the zeroth place, but not in the 2nd place. So the second 1
is eliminated.