DEV Community

Yong Liang
Yong Liang

Posted on

Remove Duplicates From Arrays in Javascript

Summary

There are several ways to remove duplicates from arrays in JS. This article will demonstrate a method using loop and indexOf() and another method using Array.from() and Set().

Method #1

  1. create a new empty array
  2. iterate through the original array
  3. use indexOf to check whether the new array already has a same value
  4. if the value is not found in the new array, then push it.
//Objective: remove the duplicate values in array1
let array1 = [1,2,3,3,4,2,5,7,1]

let array2 = []

for(let eachValue of array1){
    if(array2.indexOf(eachValue) === -1){
      array2.push(eachValue)
    }
}

console.log(array2) //returns [ 1, 2, 3, 4, 5, 7 ]

Notice that array.indexOf returns -1 if no value is found. In that case we will push the value into the empty array we have created because it is a unique value.

Method #2

  1. Set is a javascript built-in method, which allows to store unique values.
  2. since set returns collection of unique values in an object type, we need to convert this object back to an array.
  3. Array.from() method will convert the Set() object back to an array. This creates a new, shallow copied array.
//Objective: remove the duplicate values in array1

let array1 = [1,2,3,3,4,2,5,7,1]

array1 = Array.from(new Set(array1))


console.log(array1) //returns [ 1, 2, 3, 4, 5, 7 ]

We can also use the array.filter() and indexOf() to return only unique values.

Top comments (0)