Remove Duplicates From Arrays in Javascript
Yong Liang
Posted on July 27, 2019
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
- create a new empty array
- iterate through the original array
- use indexOf to check whether the new array already has a same value
- 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
- Set is a javascript built-in method, which allows to store unique values.
- since set returns collection of unique values in an object type, we need to convert this object back to an array.
- 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.
💖 💪 🙅 🚩
Yong Liang
Posted on July 27, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
watercooler Why does a reboot make your PC run SO much faster than running all the cleaning tools you can possibly imagine?
November 30, 2024