Remove Duplicate Items from an Array in JavaScript

- 1 minute read

JavaScript has a very powerful built-in Set object that is used for storing unique values, regardless of type. For example, we can use Set to remove all the duplicate items from a given array:

const removeDuplicates = (array) => {
    return [...new Set(array)];
};

The removeDuplicates function could be used like this:

const oldArray = [1, 1, 2, 2, 3, 3];

const newArray = removeDuplicates(oldArray);

After the above code has executed, newArray will equal [1, 2, 3]. This is just oldArray but without the duplicate items.

If there weren’t any duplicate items, then the returned value for newArray would be identical to the value of oldArray.

Link to this section One-liner to remove duplicates

This is a one-liner variant of our removeDuplicates function with the exact same behavior:

const removeDuplicates = (array) => [...new Set(array)];

Link to this section Conclusion

As much as I’d like to talk more about the Set object and its massive versatility, I’ll wrap this up before I get carried away.

Anyway, I hope this article helped you with removing your duplicate array items!