• Post category:JavaScript
  • Reading time:4 mins read

In this article, you will show you how to remove duplicates from an Array in JavaScript.

There are multiple ways to remove duplicates from an array and return the unique values. Here we explain you three different ways to do this task.

Way to remove duplicate values from an array in JavaScript

  1. Set()
  2. filter()
  3. forEach()

1. Set()

In our opinion set method is the simplest and shortest way to get unique values. ES6 provides the Set object which lets you store unique values. We just need to pass an array as a parameter to set object, it will remove the duplicate values.

var colors = ["Blue","Green","Yellow","Pink","Green"];
var uniqueColors = [...new Set(colors)];
console.log(uniqueColors);

// Output: ["Blue", "Green", "Yellow", "Pink"]

Here, first we create set object by passing an array so, duplicate values will be removed. Then using spread operator (…) , we convert it back to an array.

Also you can use Array.form() to convert a Set into an array.

var colors = ["Blue","Green","Yellow","Pink","Green"];
var uniqueColors = Array.from(new Set(colors));
console.log(uniqueColors);

// Output: ["Blue", "Green", "Yellow", "Pink"]

2. filter()

Using filter() method, you can also remove duplicate values from an array. See below example.

var colors = ["Blue","Green","Yellow","Pink","Green"];
var x = (colors) => colors.filter((v,i) => colors.indexOf(v) === i);
x(colors); 

// Output: ["Blue", "Green", "Yellow", "Pink"]

3. forEach()

forEach() is another way to filter out duplicates and returns unique values.

    function removeDuplicates(array){
        var colorArray = [];         

        for(i=0; i < array.length; i++){
            if(colorArray.indexOf(array[i]) === -1) {
                colorArray.push(array[i]);
            }
        }
        return colorArray;
    }   

var colors = ["Blue","Green","Yellow","Pink","Green"];
var uniqueColor =  removeDuplicates(colors)   
console.log(uniqueColor); 
   
// Output: ["Blue", "Green", "Yellow", "Pink"]

Thank you for reading. Happy Coding..!!

Leave a Reply