Remove duplicated array items in JavaScript
Hello Coders! π π
In this short article, I would like to show you how to remove duplicated items from an array in JavaScript.
In this quick solution, I've used the built-in filter()
function which has been added to improve functional programming.
If an index with the same value is found on another position, it won't be saved (in other words, it saves only those that occurred for the first time, it does not take into account the next ones).
Runnable example:
xxxxxxxxxx
const array = [1, 2, 3, 1, 1, 2, 2, 3, 3];
const result = array.filter((item, index, array) => array.indexOf(item) === index);
β
console.log(JSON.stringify(result)); // [1,2,3]
In this approach, I've used a blocker
object that represents a map of elements that have already occurred. The for
loop iterates only once over all elements adding to this map and if an element has already appeared, it won't add it again.
This solution is more optimal because it has lower computational complexity. πβ
Runnable example:
xxxxxxxxxx
const removeDuplicates = (array) => {
const result = [];
const blocker = {}; // prevents against item duplication
for (const item of array) {
if (blocker.hasOwnProperty(item)) {
continue;
}
blocker[item] = true;
result.push(item);
}
return result;
};
β
// Usage example:
β
const array = [1, 2, 3, 1, 1, 2, 2, 3, 3];
const uniqueItems = removeDuplicates(array);
β
console.log(JSON.stringify(uniqueItems)); // [1,2,3]
By conversion from Array
to Set
and back we are able to remove duplicated items too.
xxxxxxxxxx
const array = [1, 2, 3, 1, 1, 2, 2, 3, 3];
β
const set = new Set(array);
const uniqueItems = Array.from(set);
β
console.log(JSON.stringify(uniqueItems)); // [1,2,3]
Thank you for your time! I hope you like the solutions. π
See you in upcoming posts! π₯π