Lessons · JavaScript · Set removes duplicates
A collection that refuses duplicates
A Set holds each value once and answers has() instantly.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
Deduplicating, 'have I seen this', membership against a big list.
How to think about it
Do I care about order, or about duplicates? Duplicates gone and order not important: [...new Set(arr)]. Need to keep first-seen order: walk the array with a Set as memory.
Worked example
const tags = ["a", "b", "a"];One repeat.
new Set(tags).size;2.
[...new Set(tags)];["a", "b"]: unique, in first-seen order. The semicolon on the line above matters: a line starting with [ otherwise joins onto it as an index.
Your turn
Is there any repeat?
const hasRepeat = new Set(items).size items.length;
Solve one with the tests running
The trap
Sets compare objects by reference, so two equal-looking objects are two entries.
Practise Set removes duplicates on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.