How to remove duplicate array values

Last updated: December 1, 2022.

It is not uncommon to find yourself wanting to remove duplicates values from an array.

A simple but relatively slow way to do this is using Set() constructor.

A Set object is an array-like collection of unique values.

When creating a new Set object, you can pass in an array to the constructor and duplicate values will be removed in the process:

const myArray = ["Lisa", "Mark", "Lisa", "Mark"];

const mySet = new Set(myArray)
// Creates new Set object

const myUniqueArray = [...mySet];
// Spread array-like Set object contents into a new array

console.log(myUniqueArray);
// [ "Lisa", "Mark" ];

This solution requires relatively little code because it isn’t necessary to program the duplicate removal.

But it is relatively slow compared to the next solution.

More code but faster with filter()

Filter can remove duplicates as follows:

const myArray = ["Lisa", "Mark", "Lisa", "Mark"];

const uniqueArray = myArray.filter((item, index, arr) => {

    return arr.indexOf(item) === index;
    // returns true if index of first appearance of item in array matches current index

});

The key to this code is that arr.indexOf(item) will return the index of the index of the first occurence of item.

If the current item is the first instance, the comparison returns true and the value is stored in the new array that filter() returns.

If a value is not the first instance, it is a duplicate, and omitted from the new array.