Checkout my Getting Started with React video course on Skillshare. It is 100% free.

JS Interview question: removing duplicates from an array

I was making a list of common interview questions for junior front-end developers. One common question that pops up quite often is how to remove duplicates from a JavaScript array.

Let's say we have to the following array:

const withDuplicates = ["dog", "cat", "dog", "cow", "dog", "cat"]

To keep just the unique values we will have:

const uniqueValues = [...new Set(withDuplicates)]
// it will return ["dog", "cat", "cow"]

Bam, that's all! Just one line!

It works as well with numeric values but does not work with objects.

The Set is a Javascript data structure and its main purpose is to be a container for data that can’t be repeated.

By initializing a Set with a destructured array (the ... operator before new Set()), we pass the actual values the Set will automatically remove the duplicates. Finally, we convert it back to an array by wrapping it into square brackets.

The Set was added in 2015 by the ES6 version of Javascript.

The old complex solution without using the ES6 Set

Before having Sets in Javascript we had to do this manually with a code similar to this one:


function remove_duplicates(arr) {
    var obj = {};
    var ret_arr = [];
    for (var i = 0; i < arr.length; i++) {
        obj[arr[i]] = true;
    }
    for (var key in obj) {
        ret_arr.push(key);
    }
    return ret_arr;
}