Remove duplicate values from array in JavaScript

How to remove duplicate values from array using JavaScript

Posted by Ervin Adams on September 2, 2022

Remove duplicate values from array in JavaScript

How to remove duplicate values from array using JavaScript

Posted by Ervin Adams on September 2, 2022

Here are a few ways in which you can remove duplicate values from array using JavaScript.

Option 1. Use for loop

let arr=[5,11,6,8,2,5];
let newArr = [];

for (i=0; i<arr.length; i++) {  
    if (!newArr.includes(arr[i])) {
        newArr.push(arr[i]); 
    }
}
console.log(newArr); //[5,11,6,8,2]

Option 2. Use a set

let arr=[5,11,6,8,2,5];
let newArr = [];

newArr = [...new Set(arr)];

console.log(newArr); //[5,11,6,8,2]

Option 3. Use filter and index

let arr=[5,11,6,8,2,5];
let newArr = [];

newArr = arr.filter((e, i) => {
  return arr.indexOf(e) === i;
});
console.log(newArr); //[5,11,6,8,2]