3 WAYS TO REMOVE ARRAY DUPLICATES IN JAVASCRIPT

Kanchanabj
Jan 29, 2021
  1. USING SET: Set is a new data object introduced in ES6.Because set only lets you store unique values. When you pass in an array it will remove any duplicates.

const dataArr = [‘1’, ‘5’, ‘6’, ‘1’, ‘3’, ‘5’, ‘90’, ‘334’, ‘90’];

const dataArrWithSet = new set(dataArr);

const resultArr = […dataArrWithSet];

console.log(resultArr);

2.USING REDUCE: reduce is a method of array prototype which have reducer function which executes on each element and results in a single output value.

const dataArr = [‘1’, ‘5’, ‘6’, ‘1’, ‘3’, ‘5’, ‘90’, ‘334’, ‘90’];

const resultArr = dataArr.reduce((acc, item)=>{

if(!acc.includes(item)){

acc.push(item);

}

return acc;

},[])

console.log(resultArr);

3.USING FOREACH METHOD: forEach is a method of array prototype which used to iterate over elements of the array.

const dataArr = [‘1’, ‘5’, ‘6’, ‘1’, ‘3’, ‘5’, ‘90’, ‘334’, ‘90’];

const uniqueArr = [];

dataArr.forEach((item)=>{

if(!uniqueArr.includes(item)){

uniqueArr.push(item);

}

})

console.log(uniqueArr);

--

--