Sub topic 6
Iterating Sets and Removing Duplicates
This chapter assumes you know how to create a Set and use add, has, delete, and size. It also assumes you are comfortable with for...of loops, the spread operator, and arrow functions. Here you will learn the order in which a Set gives back its values, the iteration methods it shares with Map, and how to use a Set to remove duplicates from an array.
Sets Iterate in Insertion Order
A Set returns its values in the order they were first added. If you add a value that is already in the Set, nothing happens, and the value keeps its original position. To move a value to the end, delete it and then add it again.
const letters = new Set(['a', 'b', 'c']);
letters.add('a'); // already present: position unchanged
letters.delete('b');
letters.add('b'); // re-added: now last
for (const letter of letters) {
console.log(letter); // 'a', then 'c', then 'b'
}The Iteration Methods
A Set has the same iteration methods as a Map. A Set has no separate keys, though, so each value also stands in for its key.
| Method | Yields | Notes |
|---|---|---|
| `values()` | each value | Also the default iterator used by `for...of` |
| `keys()` | each value | Alias of `values()`, kept for parity with Map |
| `entries()` | `[value, value]` | The value is repeated so the shape matches Map entries |
| `forEach(cb)` | calls `cb(value, value, set)` | The second argument repeats the value |
const colors = new Set(['red', 'green']);
console.log([...colors.keys()]); // ['red', 'green']
console.log([...colors.entries()]); // [['red', 'red'], ['green', 'green']]
colors.forEach((value, key, set) => {
console.log(value === key, set === colors); // true true
});Because a Set and a Map share this API, a function written for entries() or forEach can accept either one.
Removing Duplicates from an Array
A Set stores each value only once and keeps insertion order. That makes it a short way to deduplicate an array. Pass the array to the constructor, then spread the Set back into a new array. Array.from(set) gives the same result.
const scores = [90, 75, 90, 60, 75];
const unique = [...new Set(scores)];
console.log(unique); // [90, 75, 60]
console.log(Array.from(new Set(scores))); // [90, 75, 60]Common Error: Deduplicating Objects
A Set compares objects by reference. Two objects that look the same are still two separate values, so new Set will not merge them. To deduplicate objects by a field, put the field values in a Set and use it to track what you have already seen:
const users = [
{ id: 1, name: 'Ana' },
{ id: 2, name: 'Ben' },
{ id: 1, name: 'Ana B.' }
];
console.log(new Set(users).size); // 3: every object is distinct
const seenIds = new Set();
const uniqueUsers = users.filter((user) => {
if (seenIds.has(user.id)) return false;
seenIds.add(user.id);
return true;
});
console.log(uniqueUsers.map((u) => u.name)); // ['Ana', 'Ben']This approach keeps the first object for each id, and each has check is fast.
Exercise
What does this code log, and why? const s = new Set([3, 1, 2]); s.add(3); s.delete(1); s.add(1); console.log([...s]);
Show answer
It logs [3, 2, 1]. Adding 3 again does nothing because 3 is already in the Set, so it stays first. Deleting 1 and adding it back makes it a new insertion, so it moves to the end.
Exercise
Write one line that returns the distinct words in the array words, keeping the order in which each word first appears.
Show answer
const distinct = [...new Set(words)]; A Set keeps only the first occurrence of each string, and it iterates in insertion order, so the spread produces the words in first-seen order.