How to remove duplicates from array quickly without loop in JavaScript?

← PrevNext →

You can use the Spread (...) operator along with the Set object in JavaScript, to remove duplicates from an array without running a loop. Its not only quick but its also clean. Let me show you how.

Example 1

<script>
    let removeDuplicates = () => {
        let arr = [1,1,2,2,3,4];
        const set = new Set (arr);
        document.write(...set);
    }

    removeDuplicates();     // Output: 1234
</script>
Try it

If you see the output of the above script, it has removed all the duplicates and returned unique numbers only. There are two important that you need to understand. One, the Set object and two, the Spread operator.

Set object

The Set object allows you to store unique values only. No duplicates are allowed within Sets. It only stores a unique collection of values.

So when I assigned the array to the Set (Set(arr)), it retured only the unique numbers. However, it does not alter the array. The original array remains the same.

The Set object is one of the most effient ways to manage distinct values in JavaScript.

To avoid running a loop, I am using the "Spread operator".

I have explained about JavaScript Spread Operator in detail here.

Now, lets see some more examples.

➡️ JavaScript Operators

Example 2

In this example, I have an array of string value and I'll extract unique items (or values) using the "Set" object.

The item "pen" is added twice and I want only the distinct items.

<script>
    let removeDuplicates = () => {
        let arr = ['pen', 'ruller', 'pen', 'eraser', 'printer'];
        const set = new Set (arr);
        document.write([...set].join(' '));
    }

    removeDuplicates();     // Output: pen ruller eraser printer
</script>
Try it

I don't know if you have noticed or not, there's a slight difference between the 1st example and the 2nd exmaple, while using the Spread operator. In this example (the 2nd example), I have defined the spread within square [] bracket. So I can use the .join() method to add a space between each item.

← PreviousNext →