Arrays and algorithms · beginner
JavaScript Program to Remove Duplicates from an Array
Remove duplicate values from a JavaScript array with a Set, with filter() and indexOf(), and remove duplicate objects by a key such as an id.
- Set
- spread syntax
- filter()
- Map keyed by id
new Set(array) keeps only the first occurrence of each value, and it remembers insertion order, so [...new Set(array)] removes duplicates without changing the order. That one line covers numbers and strings.
Objects are different: two objects with the same contents are still different values, so duplicates have to be removed by a key.
The program
const fruits = ["apple", "banana", "apple", "cherry", "banana", "date"];
const unique = [...new Set(fruits)];
console.log(unique.join(", "));
const seen = new Set();
const manual = [];
for (const fruit of fruits) {
if (!seen.has(fruit)) {
seen.add(fruit);
manual.push(fruit);
}
}
console.log(manual.join(", "));apple, banana, cherry, date
apple, banana, cherry, dateHow it works
- new Set(fruits) stores each value once; [...] spreads it back into an array in the original order.
- The loop version shows what Set does: remember the values already seen and skip them.
- seen.has() is fast even for large arrays, unlike searching an array with includes().
Watch it run line by line
In the loop, watch seen and manual grow together. On the second "apple", the if test is false and neither changes.
“Visualize step by step” opens the program in the JavaScript Compiler and records every step in your browser. Use the arrow keys to move forwards and backwards; changed variables are highlighted.
Another way: Objects: remove duplicates by id
A Map keyed by id keeps one object per id. Setting a key again keeps its original position, so the first object's place is kept but the last object with that id wins.
const users = [
{ id: 1, name: "Ada" },
{ id: 2, name: "Linus" },
{ id: 1, name: "Ada L." },
];
const byId = [...new Map(users.map((user) => [user.id, user])).values()];
console.log(JSON.stringify(byId));
console.log(new Set([{ id: 1 }, { id: 1 }]).size);[{"id":1,"name":"Ada L."},{"id":2,"name":"Linus"}]
2Common mistakes
- Expecting new Set() to remove duplicate objects: { id: 1 } and { id: 1 } are two different objects, so the Set keeps both.
- Using filter((x, i) => array.indexOf(x) === i) on long arrays: it works but checks the whole array for every element.
- Forgetting the spread: new Set(fruits) is a Set, not an array, so join() and map() are not available on it.
Try it yourself
- Remove duplicates while ignoring case, so "Apple" and "apple" count as one.
- Return only the values that appear more than once.
Open the program in the JavaScript Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.
Related examples
Browse all 25 JavaScript examples, or write your own program in the online JavaScript Compiler.