When working with arrays in JavaScript, you’ll often run into duplicate values. Removing them efficiently not only keeps your data clean but also makes your code more optimized. Let’s look at the most common ways of how to remove duplicates from a JavaScript array.
Set (ES6+)const numbers = [1, 2, 2, 3, 4, 4, 5];
const uniqueNumbers = [...new Set(numbers)];
console.log(uniqueNumbers); // [1, 2, 3, 4, 5] ✅ Simple and efficient
✅ Best for modern JavaScript
filter() + indexOf()const numbers = [1, 2, 2, 3, 4, 4, 5];
const uniqueNumbers = numbers.filter((value, index) =>
numbers.indexOf(value) === index
);
console.log(uniqueNumbers); // [1, 2, 3, 4, 5] ✅ Works everywhere
⚠️ Slightly slower on large arrays
reduce() + includes()const numbers = [1, 2, 2, 3, 4, 4, 5];
const uniqueNumbers = numbers.reduce((acc, value) => {
if (!acc.includes(value)) acc.push(value);
return acc;
}, []);
console.log(uniqueNumbers); // [1, 2, 3, 4, 5] ✅ Great for learning array methods
forEach() + Object Lookupconst numbers = [1, 2, 2, 3, 4, 4, 5];
const lookup = {};
const uniqueNumbers = [];
numbers.forEach(num => {
if (!lookup[num]) {
lookup[num] = true;
uniqueNumbers.push(num);
}
});
console.log(uniqueNumbers); // [1, 2, 3, 4, 5] ✅ Very fast for larger datasets
The Set method is the easiest and most modern solution, but depending on the scenario (browser support, performance needs), other approaches can still be useful.
How to remove duplicates from a JavaScript array is a common task with many solutions. The most modern and efficient method is using Set, while traditional methods like filter() + indexOf(), reduce() + includes(), or a lookup object offer alternatives depending on performance needs and project requirements. The key takeaway: JavaScript gives you multiple tools to keep your data clean—pick the one that best fits your use case.
Latest tech news and coding tips.
Why borrowing code is a skill—when you understand what you're copying. For years, "copy-paste developer"…
Interactive forms rarely keep every field active all the time. Sometimes an input should only…
A modern JavaScript API for working with dates, times, time zones, and calendars without the…
Understanding What Happens Behind the Scenes Node.js looks simple from the outside—you write JavaScript, call…
The need for absolute certainty is the greatest disease the engineering mind faces. The moment…
The software industry is one of the most competitive places to build a career. Every…