Remove Duplicates from an Array with JavaScript

This way of removing duplicates is quite simple and elegant, thanks to the methods Array.filter() and Array.indexOf().

The Array.filter() method creates a new array from an existing one, which contains only the elements that meet the filter criteria. The Array.indexOf() method, on the other hand, returns the index of the first element of an array whose value matches the one passed to it as a parameter.

The algorithm to eliminate the duplicates works in this way:

  1. In the callback of Array.filter(), we will use Array.indexOf() to obtain the index of the first element that matches with the current element of the loop of our original array.
  2. If that index matches the index of the current element in the loop, we will add it to the result array. If not, it is a duplicate entry and we will ignore it.

Here is an example to make it clearer:

Why does this work?

Let’s look at the entry “computer1”, which appears twice, in indexes 0 and 4. The method computers.indexOf(computer) will return 0 for each instance of “computer1”, because it returns the index of the first matching element.

The first time “computer1” appears, the values of indexOf(computer) and index match, so it is added to our result array. The next time it does not (4 is different from 0), and is ignored.

--

--