Remove duplicates from an Array with JavaScript
Very often we need to remove all duplicates in an array, and in JavaScript, we can do this in several ways.
Filter method
Filter method creates a new array by calling a callback function we provide as the first argument. The callback function takes three arguments (current iterated item, index of the current iterated item, array instance) and runs for each item in the array. As result, a new array has elements that accomplish condition in the callback function, if an element pass a condition it returns true, and will be added to a new array.
Method indexOf returns the first index of the array where the given element was found.
const arr = [2, 33, 55, 5, “hello”, 33, 2, 44, “hello”];const filteredResults = arr.filter((item, index) => arr.indexOf(item) === index);console.log(filteredResults); //[2, 33, 55, 5, “hello”, 44];
Method reduce
Method reduce takes as argument function callback and initial value (empty array in our case). The callback function executes for every element in an array and returns that type of data that we have as finial value. The callback function receives two arguments - accumulator and current iterated item. Accumulator, it is a value that was returned from the last iteration in our callback function, the first time it will be an empty array — our initial value.
In a body of the callback function we are going to check if no same value in the accumulator we push it.
const arr = [2, 33, 55, 5, “hello”, 33, 2, 44, “hello”];const reducedResult = arr.reduce((acc, item) => {
if (!acc.includes(item)) {
acc.push(item);
}
return acc;
}, []);console.log(reducedResult); // [2, 33, 55, 5, “hello”, 44];
Method forEach
Method forEach iterates over the array items, not mutating the array. It executes the callback function that receives three arguments — the current iterated item, the index of the item.
We create an empty array where non duplicated values will be held. In the body of the callback function, we check if in the new array includes iterated value, if no we push it there.
const arr = [2, 33, 55, 5, “hello”, 33, 2, 44, “hello”];const forEachResult = [];arr.forEach((item) => {
if (!forEachResult.includes(item)) {
forEachResult.push(item);
}
});console.log(forEachResult); //[2, 33, 55, 5, “hello”, 44];
Set object
Set object is a special kind of collection, where each value can appear only once. So for transforming Set collection to an array we are using speed operator [… ].
const arr = [2, 33, 55, 5, "hello", 33, 2, 44, "hello"];const setResult = [...new Set(arr)];console.log(setResult); //[2, 33, 55, 5, "hello", 44];