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.
Quick solution
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:
// 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]
Iterative example
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:
// 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]
Set
based example
By conversion from Array
to Set
and back we are able to remove duplicated items too.
// ONLINE-RUNNER:browser;
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! 🔥🔜