Remove Duplicates from an Array
Serhii Shramko /
Initial array:
const numbers = [1, 1, 1, 3, 3, 2, 2, 5, 6, 7, 7];
Using a Set
const uniqueNumbers = [...new Set(numbers)];
Array.prototype.reduce
const uniqueNumbers = numbers.reduce((previousValue, currentValue) => {
return previousValue.includes(currentValue) ? previousValue : [...previousValue, currentValue];
}, []);
If you are not familiar with reduce
, use
this documentation.
Array.prototype.filter
const uniqueNumbers = numbers.filter((element, index) => {
return numbers.indexOf(element) === index;
});