4 ways for removing duplicated in arrays using Javascript
Remove duplicated arrays is a common task in Javascript, in the next post we will see many ways to overcome to this situation, from simpler and modern to classic old ones
1.Using Set
(recommended)
Set
allows us to store the unique values, so converting a normal array with duplicated values using Set
is the most easy and fastest solution.
const array = [1, 2, 3, 4, 4, 5, 5, 6];
const uniqueArray = [...new Set(array)];
console.log(uniqueArray); // [1, 2, 3, 4, 5, 6]
2.Using filter
and indexOf
Another way of removing duplicated values is using filter
and indexOf
for checking its index, so this is used to be sure that the element only appears once.
const array = [1, 2, 3, 4, 4, 5, 5, 6];
const uniqueArray = array.filter((item, index) => array.indexOf(item) === index);
console.log(uniqueArray); // [1, 2, 3, 4, 5, 6]
3.Using reduce
We can use the method reduce
to store the elements in uniques in a new array.
const array = [1, 2, 3, 4, 4, 5, 5, 6];
const uniqueArray = array.reduce((acc, item) => {
if (!acc.includes(item)) {
acc.push(item);
}
return acc;
}, []);
console.log(uniqueArray); // [1, 2, 3, 4, 5, 6]
4.Using forEch
and Object
Another way could be using forEach
for iterate over the array and using Objct for storing the unique values, then convert the keys of the Object to an array again.
const array = [1, 2, 3, 4, 4, 5, 5, 6];
const uniqueObj = {};
array.forEach((item) => {
uniqueObj[item] = true;
});
const uniqueArray = Object.keys(uniqueObj).map(Number);
console.log(uniqueArray); // [1, 2, 3, 4, 5, 6]
The good ✅ and the bad ❌
Método | Ventajas | Desventajas |
---|---|---|
Set | Simple and efficient | No support for older versions of IE |
filter and indexOf | Easy to understand | Not suitable for big arrays |
reduce | Useful and functional | Complex for reading |
forEch | Easy to understand and implement | Too much code and inefficient |
Conclusion
Me as a programmer I use the Set method because of readability, performance and because in my job we don’t support old browsers like IE o Netscape