EN
JavaScript - remove duplicates from array
15
points
In this short article, we would like to show how to remove duplicated items in an array in JavaScript.
Quick solution:
// ONLINE-RUNNER:browser;
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]
Reusable function example
The below approaches reduce the number of iterations.
1. Set
based approach
// ONLINE-RUNNER:browser;
const removeDuplicates = (array) => {
const result = [];
const blocker = new Set(); // prevents against item duplication
for (const item of array) {
if (blocker.has(item)) {
continue;
}
blocker.add(item);
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]
2. Simple types approach
This solution should be used when each item has the same type in the array, and the type is one of: boolean, number or string.
// ONLINE-RUNNER:browser;
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]