This page looks best with JavaScript enabled

Use Filter to Eliminate Duplicates in Javascript Array

 ·   ·  ☕ 1 min read

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 -

1
const nums = [1, 5, 0, 1, 2, 3];

The below code will create a unique array.

1
2
3
4
5
const uniqueNums = nums.filter((num, index) => {
  return nums.indexOf(num) == index;
});

console.log(uniqueNums); // [ 1, 5, 0, 2, 3 ]

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.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things