JavaScript Set: Dedupe Arrays, Union, Intersection and Fast Lookups
A JavaScript Set stores unique values of any type. Learn add, has and delete, the one-line way to remove duplicates, the new built-in union and intersection methods, how Set decides two values are equal, and how much faster has() was in our test.
- A JavaScript Set keeps each value once and remembers insertion order.
[...new Set(arr)]removes duplicate primitives from an array in one line.- Node 24 supports the new built-in
union,intersection,differenceandsymmetricDifferencemethods; they return new sets and leave the inputs untouched. - For 1,000 lookups in 100,000 items,
set.hastook 0.065 ms versus 118.7 ms forarray.includesin our run.
You have a list of tags with repeats, two lists of user IDs to compare, or a hot loop that keeps asking “have I seen this before?”. The JavaScript Set is the built-in answer to all three. It stores unique values, checks membership quickly, and, since the 2025 edition of the language, does union and intersection without any helper code.
Every output in this guide came from running the code with Node.js v24.22.1. Browsers print sets slightly differently in the console, but the behaviour is the same.
What is a Set in JavaScript?
A Set is a collection of values where each value can appear only once. Unlike an object, its values can be of any type: numbers, strings, objects, functions, even NaN. Unlike an array, it has no indexes, so you cannot read set[0]. You ask whether a value is in it, add values, remove them and loop over them.
If you know Python sets, the idea is the same, with one difference covered below: a JavaScript Set keeps the order in which you added items.
add, has, delete and size
const s = new Set([3, 1, 3, 2, 1]);
console.log(s, s.size);
s.add(4).add(4); // add returns the set, so calls chain
console.log(s.has(4), s.delete(9), [...s]);
Set(3) { 3, 1, 2 } 3
true false [ 3, 1, 2, 4 ]
The constructor dropped the duplicate 3 and 1. Adding 4 twice stored it once. delete returns false when the value was not there, which is handy for knowing whether anything changed. Note that size is a property, s.size, not a method and not length. Use s.clear() to empty a set.
Remove duplicates from an array
This is the most common use of a Set. Spread a new Set back into an array:
console.log([...new Set(["qa", "dev", "qa", "ops", "dev"])]);
[ 'qa', 'dev', 'ops' ]
The first occurrence of each value wins, and the original order is kept. Array.from(new Set(arr)) does the same thing. It also works on strings, because a string is iterable:
console.log(new Set("banana")); // Set(3) { 'b', 'a', 'n' }
Our JavaScript spread operator guide explains why the ... syntax works on any iterable.
How Set decides two values are equal
Set uses an algorithm called SameValueZero. It is almost the same as ===, with one important difference:
console.log(new Set([NaN, NaN, 0, -0])); // Set(2) { NaN, 0 }
NaN === NaN is false, yet the Set kept only one NaN. And 0 and -0 count as the same value. Strings are compared by content, so "1" and 1 are different members. That last point bites when IDs arrive as strings from a URL but numbers from a database: convert them to one type before adding.
Objects and arrays in a Set
Objects are compared by reference, not by content:
console.log(new Set([{id: 1}, {id: 1}]).size, new Set([[1], [1]]).size); // 2 2
Two objects that look identical are still two different objects, so both stay. To deduplicate records by a field, key them by that field with a Map instead:
const unique = [...new Map(users.map(u => [u.id, u])).values()];
That keeps the last record for each ID. If you need the first, check map.has(u.id) before setting.
Order and iteration
A Set iterates in insertion order. Deleting a value and adding it again moves it to the end:
const ins = new Set();
ins.add("c"); ins.add("a"); ins.add("b");
ins.delete("a"); ins.add("a");
console.log([...ins]); // [ 'c', 'b', 'a' ]
You can loop with for (const v of set), set.forEach, or the values(), keys() and entries() iterators. Because sets have no keys, forEach passes the value twice; we confirmed the key and value arguments are identical. Array methods like map and filter are not on Set, so spread to an array first: [...set].filter(fn). Our JavaScript array methods guide covers those.
Union, intersection and difference (new built-ins)
Seven methods were added to Set.prototype in ECMAScript 2025. They are available in current Chrome, Firefox and Safari, and in Node 22 and later. We tested them on Node 24:
const a = new Set([1, 2, 3, 4]), b = new Set([3, 4, 5]);
console.log("union", a.union(b));
console.log("intersection", a.intersection(b));
console.log("difference", a.difference(b));
console.log("symDiff", a.symmetricDifference(b));
console.log("input unchanged", a);
union Set(5) { 1, 2, 3, 4, 5 }
intersection Set(2) { 3, 4 }
difference Set(2) { 1, 2 }
symDiff Set(3) { 1, 2, 5 }
input unchanged Set(4) { 1, 2, 3, 4 }
| Method | Returns | Example use |
|---|---|---|
a.union(b) |
items in either | All permissions from two roles |
a.intersection(b) |
items in both | Users in both campaigns |
a.difference(b) |
items in a, not b | Tests that ran yesterday but not today |
a.symmetricDifference(b) |
items in exactly one | Config keys that differ between environments |
None of them mutate a or b. The argument must be set-like: it needs a size property plus has and keys methods. Passing a plain array fails, as we found:
new Set([1, 2]).union([2, 3]);
// TypeError: The .size property is NaN
Wrap the array first: a.union(new Set(arr)). A Map works as an argument, because it has size, has and keys.
Subset, superset and disjoint checks
console.log(
new Set([3, 4]).isSubsetOf(a), // true
a.isSupersetOf(new Set([1, 9])), // false
a.isDisjointFrom(new Set([7, 8])) // true
);
These return booleans. isSubsetOf is a neat way to check that a user has every required permission, and isDisjointFrom confirms two groups share nothing, for example that a test data set has no overlap with production IDs. The same set ideas power Jaccard similarity, which divides the intersection size by the union size.
Union and intersection in older environments
If you must support older browsers or Node 20, the spread and filter versions still work and gave identical results in our run:
const union = new Set([...a, ...b]);
const inter = new Set([...a].filter(x => b.has(x)));
const diff = new Set([...a].filter(x => !b.has(x)));
Use b.has(x) inside the filter, not arrayB.includes(x). The next section shows why.
Set vs array: lookup speed we measured
We built an array and a Set with 100,000 numbers, then looked up 1,000 values near the end of the array with each:
1000 lookups: array.includes 118.7 ms, set.has 0.065 ms
includes scans the array from the start every time, so its cost grows with the array length. has uses a hash table and stays roughly constant. Building the Set costs a single pass, so if you check membership more than a handful of times, convert once and reuse it. Exact numbers will vary by machine and engine, but the gap of more than a thousand times is typical for lookups near the end of a large array.
Tip: for a one-off check on a ten-item array, includes is perfectly fine. Reach for a Set when the list is large or the check sits inside a loop.
Sets and JSON
JSON.stringify does not know how to serialise a Set:
console.log(JSON.stringify(new Set([1, 2])), JSON.stringify([...new Set([1, 2])]));
// {} [1,2]
A Set silently becomes an empty object, which is an easy bug to ship in an API response or a localStorage write. Convert to an array before serialising, and back with new Set(JSON.parse(text)) after reading.
WeakSet in one paragraph
A WeakSet holds only objects, and holds them weakly, so an object in it can still be garbage collected when nothing else references it. It has add, has and delete but no size and no iteration. It is useful for marking objects, for example “this DOM node was already processed”. Adding a primitive throws, as our run showed: TypeError: Invalid value used in weak set.
Common mistakes
- Using length:
set.lengthisundefined. Useset.size. - Indexing:
set[0]isundefined. Spread to an array or useset.values().next().value. - Expecting object dedupe: identical-looking objects are different members. Dedupe by key with a Map.
- Mixing types:
"5"and5are different values. - Passing arrays to the new methods: wrap them in
new Set()first. - Serialising a Set directly: convert to an array before
JSON.stringify.
Final thoughts
The JavaScript Set is small but useful: one line removes duplicates, has turns slow scans into near-instant lookups, and the new union, intersection and difference methods replace helper code you used to copy between projects. Remember that objects are compared by reference, that the new methods need set-like arguments, and that JSON needs an array, and Sets will save you time in everyday code.
Frequently asked questions
How do I remove duplicates from an array in JavaScript?
Create a Set from the array and convert it back with Array.from(new Set(arr)) or the spread syntax. It keeps the first occurrence of each value in its original order. For objects, dedupe by a key with a Map.
Does JavaScript Set have union and intersection methods?
Yes. ECMAScript 2025 added union, intersection, difference, symmetricDifference, isSubsetOf, isSupersetOf and isDisjointFrom. They work in current browsers and Node 22 or later.
Does a Set keep insertion order?
Yes. A JavaScript Set iterates in the order values were first added. Deleting a value and adding it again moves it to the end.
Is Set.has faster than Array.includes?
For large collections, yes. In our test with 100,000 items, 1,000 has calls took 0.065 ms while includes took 118.7 ms, because includes scans the array each time.
Why does JSON.stringify return an empty object for a Set?
A Set stores its values internally, not as enumerable properties, so JSON sees an empty object. Convert it to an array with the spread syntax or Array.from before serialising.
Keep learning
Need help with testing, WordPress or SEO?
We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.