Sub topic 6
Iterating Sets and Removing Duplicates
This chapter assumes you already know how to create a Set and use add, has, and delete, and that you know Sets compare values with SameValueZero. It also relies on for...of, the spread operator, and the array methods filter and map. The focus here is how a Set gives its values back to you and how to use that to remove duplicates from data.
The Iteration Methods
A Set is iterable, so for...of and spread work on it directly. It also has methods that return iterators. An iterator is an object that produces values one at a time when asked. All of these methods visit values in insertion order.
| Method | Yields | Notes |
|---|---|---|
| `set[Symbol.iterator]()` | each value | Used by `for...of` and spread; same function as `values` |
| `values()` | each value | The main iterator |
| `keys()` | each value | Alias of `values`, kept so Set matches Map's API |
| `entries()` | `[value, value]` pairs | Key and value are the same item |
| `forEach(cb)` | calls `cb(value, value, set)` | Has no `break`; returns `undefined` |
const letters = new Set(['a', 'b', 'c']);
for (const letter of letters) {
console.log(letter); // 'a', then 'b', then 'c'
}
console.log([...letters.keys()]); // ['a', 'b', 'c']
console.log([...letters.entries()]); // [['a', 'a'], ['b', 'b'], ['c', 'c']]
letters.forEach((value, sameValue, set) => {
console.log(value === sameValue, set === letters); // true true
});The repeated value in entries() and in the forEach arguments can look odd. It exists so that code written for a Map, which expects a key and a value, also runs on a Set. Because a Set has no separate keys, it passes each value twice.
What Insertion Order Really Means
A value keeps the position it had when it was first added. If you add a value that is already present, nothing happens, so it does not move to the end. To move a value to the end, delete it and add it again.
const queue = new Set([3, 1, 2]);
queue.add(1); // already present: no change
console.log([...queue]); // [3, 1, 2]
queue.delete(3);
queue.add(3); // removed, then added back at the end
console.log([...queue]); // [1, 2, 3]The delete-then-add trick is the usual way to build a small "most recently used" list with a Set. The oldest item is always the first one the iterator returns.
Iterators Are Live and Single-Use
A Set iterator reads the Set while it runs. It does not take a snapshot first. That leads to two behaviors that often cause bugs.
First, an iterator can only be used once. After it has produced every value, it is done, and reading it again gives nothing.
const nums = new Set([1, 2, 3]);
const it = nums.values();
console.log([...it]); // [1, 2, 3]
console.log([...it]); // [] (the iterator is already exhausted)
console.log([...nums]); // [1, 2, 3] (a fresh iterator each time)Second, if you change the Set during a loop, the loop sees the change. Values you delete before the loop reaches them are skipped. Values you add are appended and will be visited.
const items = new Set([1, 2, 3]);
for (const v of items) {
if (v === 1) {
items.delete(2); // not reached yet, so it is skipped
items.add(4); // appended, so it is visited
}
console.log(v); // 1, 3, 4
}Removing Duplicates from an Array
The standard way to deduplicate an array is to pass it to the Set constructor and spread the result back into an array.
const tags = ['js', 'css', 'js', 'html', 'css'];
const unique = [...new Set(tags)];
const alsoUnique = Array.from(new Set(tags));
const upper = Array.from(new Set(tags), (t) => t.toUpperCase());
console.log(unique); // ['js', 'css', 'html']
console.log(alsoUnique); // ['js', 'css', 'html']
console.log(upper); // ['JS', 'CSS', 'HTML']
console.log([...new Set('mississippi')].join('')); // 'misp'Values keep the order of their first appearance, because a later duplicate never moves an existing entry. Strings are iterable, so the same pattern removes repeated characters. Array.from also accepts a mapping function as its second argument, which saves you a separate map call.
Why Not filter with indexOf?
You will often see this older idiom:
const data = [1, NaN, 2, NaN, 1];
const viaIndexOf = data.filter((v, i) => data.indexOf(v) === i);
const viaSet = [...new Set(data)];
console.log(viaIndexOf); // [1, 2] (NaN disappeared)
console.log(viaSet); // [1, NaN, 2]The indexOf version has two problems. indexOf uses strict equality, and NaN is never strictly equal to itself, so indexOf(NaN) returns -1 and every NaN gets filtered out. It is also slow: each indexOf call scans the array, so the total work grows with the square of the array length. A Set looks up each value in roughly constant time on average, so deduplicating with a Set takes time proportional to the array length.
Deduplicating Objects by a Field
A Set compares objects by reference. Two objects with the same contents are still two different entries. To deduplicate records by a field such as id, store the field in a Set, or key a Map by it.
const users = [
{ id: 1, name: 'Ana' },
{ id: 2, name: 'Bo' },
{ id: 1, name: 'Ana B.' }
];
// First occurrence wins: track ids you have already seen.
const seen = new Set();
const firstWins = users.filter((u) => {
if (seen.has(u.id)) return false;
seen.add(u.id);
return true;
});
console.log(firstWins.map((u) => u.name)); // ['Ana', 'Bo']
// Last occurrence wins: later set() calls overwrite the value.
const lastWins = [...new Map(users.map((u) => [u.id, u])).values()];
console.log(lastWins.map((u) => u.name)); // ['Ana B.', 'Bo']In the "last wins" version, id: 1 stays in first position even though its value was replaced. A Map keeps a key's original position when you overwrite its value, the same way a Set keeps a value's position when you add it again.
Finding the Duplicates Themselves
Sometimes you want to know which values repeat, not just remove them. Two Sets do the job in a single pass.
function findDuplicates(arr) {
const seen = new Set();
const dupes = new Set();
for (const x of arr) {
if (seen.has(x)) dupes.add(x);
else seen.add(x);
}
return [...dupes];
}
console.log(findDuplicates(['a', 'b', 'a', 'c', 'b', 'a'])); // ['a', 'b']The dupes Set makes sure a value that appears three times is reported only once.
Filtering and Mapping Without an Intermediate Array
Runtimes that support ES2025 iterator helpers (Node.js 22+, current Chrome, Firefox, and Safari) let you call filter, map, and take directly on the iterator from values(). These helpers are lazy: they process one value at a time and never build a temporary array.
const scores = new Set([12, 45, 7, 88, 45, 30]);
const highScores = new Set(scores.values().filter((n) => n >= 30));
console.log([...highScores]); // [45, 88, 30]
const firstTwo = scores.values().take(2).toArray();
console.log(firstTwo); // [12, 45]In older runtimes, use [...scores].filter(...) instead. The result is the same, but the spread builds a full array first.
Exercises
Exercise
What does this code print, and why? const s = new Set(['x', 'y', 'z']); s.add('x'); s.delete('y'); s.add('y'); console.log([...s].join(''));
Show answer
It prints 'xzy'. Adding 'x' again changes nothing because 'x' is already present, so it keeps its first position. Deleting 'y' and then adding it again puts it at the end, which gives the order x, z, y.
Exercise
Write a function uniqueBy(arr, keyFn) that returns the array with duplicates removed according to keyFn, keeping the first item for each key and preserving the original order.
Show answer
function uniqueBy(arr, keyFn) { const seen = new Set(); return arr.filter((item) => { const k = keyFn(item); if (seen.has(k)) return false; seen.add(k); return true; }); } For example, uniqueBy([{ id: 1 }, { id: 1 }, { id: 2 }], (o) => o.id) returns [{ id: 1 }, { id: 2 }].
Exercise
A colleague writes const it = mySet.values(); const count = [...it].length; const list = [...it]; and finds that list is always empty. Explain the bug and fix it.
Show answer
An iterator is used up after one full pass, so the second spread gets nothing. Spread the Set itself instead, because each spread of a Set creates a fresh iterator: const list = [...mySet]; const count = mySet.size;
Exercise
Why does [1, NaN, NaN].filter((v, i, a) => a.indexOf(v) === i) return [1], while [...new Set([1, NaN, NaN])] returns [1, NaN]?
Show answer
indexOf uses strict equality, and NaN === NaN is false, so indexOf(NaN) returns -1 and never matches the current index. Every NaN is therefore removed. A Set uses SameValueZero, which treats NaN as equal to NaN, so it keeps exactly one NaN.