How to Remove Duplicates from array in Javascript
There is many ways to remove duplicates from an array in Javascript.
I think that the simplest approach is to use Set
Object, which lets you store unique Values.
Set
will automatically remove duplicates .
Here is an example
const numbers = [1, 1, 2, 3, 4, 5, 6];
let uniqueNumbers = [...new Set(numbers)];
//uniqueNumbers = [1, 2, 3, 4, 5, 6]
a Second Option is to use the filter
const numbers = [1, 1, 2, 3, 4, 5, 6, 7];
const uniqueNumbers = numbers.filter((element, pos) => {
return numbers.indexOf(element) === pos;
});
and the Final Option is to use forEach()
const numbers = [1, 1, 2, 3, 4, 5, 6];
const uniqueNumbers = (numbers) => {
let unique = {};
numbers.forEach((element) => {
if (!unique[element]) {
unique[element] = true;
}
});
return Object.keys(unique);
};

You like our Content? Follow us to stay up-to-date.