1. Home
  2. Blog
  3. Software Development

Software Development

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.

9 min read
JavaScript Set explained: dedupe arrays, union, intersection and fast lookups

Key takeaways

  • 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, difference and symmetricDifference methods; they return new sets and leave the inputs untouched.
  • For 1,000 lookups in 100,000 items, set.has took 0.065 ms versus 118.7 ms for array.includes in 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.length is undefined. Use set.size.
  • Indexing: set[0] is undefined. Spread to an array or use set.values().next().value.
  • Expecting object dedupe: identical-looking objects are different members. Dedupe by key with a Map.
  • Mixing types: "5" and 5 are 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

Work with Stack Quora

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.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

Levenshtein Distance: Formula, Worked Table and Python Code

Levenshtein distance explained: the edit operations, the dynamic programming table for kitten and sitting, Python code with two-row memory, normalised…

Read article →
Software Development

URL Encoding Explained: Spaces, Plus Signs and UTF-8

URL encoding explained with tested Python and JavaScript code: percent encoding, reserved characters, %20 vs plus, UTF-8 bytes, encodeURI vs…

Read article →
DevOps

Gitignore: Patterns, Negation and Fixing Tracked Files

A tested gitignore guide: pattern rules, leading and trailing slashes, negation with !, the ignored parent folder trap, git check-ignore…

Read article →
Software Testing

Acceptance Criteria: Given When Then Examples and Checklist

How to write acceptance criteria testers can run: rule-based and Given When Then formats, a worked discount code example turned…

Read article →
Software Testing

State Transition Testing: Diagram, Table and Example

State transition testing explained with a login lockout example: states, events, the diagram, the state table, valid and invalid transitions,…

Read article →
Databases & SQL

Second Highest Salary in SQL: 5 Tested Ways and the Tie Trap

Find the second highest salary in SQL five ways: MAX subquery, LIMIT OFFSET, DENSE_RANK, a correlated subquery and per department,…

Read article →
Databases & SQL

SQL ROW_NUMBER: Top N per Group, Dedupe and Pagination

SQL ROW_NUMBER explained with tested queries: PARTITION BY, top N per group, deleting duplicates, pagination, the tie trap and how…

Read article →
Software Development

JavaScript Set: Union, Intersection and Removing Duplicates

JavaScript Set explained with tested examples: add, has, delete, deduplicating arrays, the new union and intersection methods, equality rules and…

Read article →
Test Automation

Python Unittest: Assert Methods, setUp and Mocks With Examples

A practical Python unittest tutorial: TestCase, assert methods, setUp and tearDown, subTest, skips, expected failures and mock, with a test…

Read article →
Software Development

Python Map and Filter: Examples vs List Comprehensions

Python map and filter explained with tested examples: lazy map objects, multiple iterables, filter(None), chaining, and a timed comparison with…

Read article →
Artificial Intelligence

Jaccard Similarity: Formula, Python, MinHash

Jaccard similarity measures overlap between two sets as intersection over union. Work the formula, compute it in Python for words…

Read article →
Software Development

Unix Timestamp Explained: Seconds vs ms

A Unix timestamp counts seconds since 1 January 1970 UTC. Learn seconds vs milliseconds, converting in Python, JavaScript and SQL,…

Read article →
DevOps

Git Hooks: Pre-commit and Commit-msg Examples

Git hooks run scripts at key moments such as commit and push. See tested pre-commit, commit-msg and prepare-commit-msg hooks, sharing…

Read article →
Test Automation

API Testing in Python: Pytest + Requests Suite

Build an API testing suite in Python with pytest and requests: fixtures, status codes, headers, JSON schema validation, CRUD flows,…

Read article →
Software Testing

Test Design Techniques: 9 Methods + Examples

Test design techniques help you write fewer tests that catch more bugs. Learn 9 black-box, white-box and experience-based methods with…

Read article →
Databases & SQL

SQL Temporary Table: Create, Use and Drop It

SQL temporary tables store interim results for one session. Learn syntax for SQL Server, PostgreSQL, MySQL, Oracle and SQLite, session…

Read article →
Databases & SQL

SQL CROSS JOIN: Every Combination + Examples

SQL CROSS JOIN returns every combination of rows from two tables. See the row math, product variants, calendar grids that…

Read article →
Software Development

JavaScript Date: Format, Parse, Timezone Bugs

JavaScript Date explained with tested Node.js code: zero-based months, the date-only UTC parsing trap, toISOString, getTimezoneOffset, Intl formatting, date math…

Read article →
Software Development

Python Requests: GET, POST, Timeouts, Retries

Python requests explained with code tested against a local API: GET with params, POST json vs data, headers and auth,…

Read article →
Artificial Intelligence

TF-IDF Explained: Formula and Worked Example

TF-IDF scores a word by how often it appears in a document and how rare it is across all documents….

Read article →
DevOps

Git Tag: Create, Push and Delete Release Tags

Git tag explained with tested commands: annotated vs lightweight tags, listing and sorting, pushing with follow-tags, deleting local and remote…

Read article →
Test Automation

Pytest Coverage: pytest-cov and Branch Gaps

Measure pytest coverage with pytest-cov: term-missing reports, branch coverage, HTML reports, pyproject settings and a fail-under gate for CI, with…

Read article →
Software Testing

Error Guessing in Testing: Checklist + Demo

Error guessing uses tester experience to predict where code breaks. Get a ready checklist of risky inputs, a step by…

Read article →
Databases & SQL

SQL LAG and LEAD: Compare Rows, 5 Examples

SQL LAG and LEAD read values from the previous or next row without a self join. Five tested examples: change,…

Read article →
Databases & SQL

SQL STRING_AGG: Combine Rows Into One String

SQL STRING_AGG joins values from many rows into one string per group. See syntax for PostgreSQL, SQL Server, MySQL GROUP_CONCAT,…

Read article →
Artificial Intelligence

BM25 Explained: How Keyword Search Ranks Results, With Python Code and Hybrid Search

BM25 explained with a pure Python implementation we ran: the formula, IDF, term saturation, the k1 and b parameters, why…

Read article →
DevOps

Git Bisect Explained: Find the Commit That Broke Your Code, Manually or Automatically

Git bisect explained with a tested repository: find the one bad commit among 41 in 5 test runs, automate it…

Read article →
Test Automation

pytest Markers Explained: Custom Marks, skip, skipif, xfail and -m Filters

pytest markers explained with a tested suite: register custom marks, run only smoke tests with -m, combine filters with and,…

Read article →
Software Testing

Positive vs Negative Testing: Differences, 24 Real Test Cases and a Checklist

Positive vs negative testing explained with a real signup form: 6 positive and 18 negative test cases run in pytest,…

Read article →
Artificial Intelligence

Cosine Similarity Explained: Formula, Worked Example and Python Code

Cosine similarity explained simply: the formula, a worked example by hand, pure Python and NumPy code, cosine vs Euclidean distance…

Read article →
DevOps

Git Squash Commits: 4 Easy Ways, Tested Step by Step (rebase -i, reset, merge)

Git squash commits explained with 4 tested methods: interactive rebase, reset –soft, merge –squash and fixup with autosquash. Before-and-after logs,…

Read article →
Test Automation

pytest parametrize Explained: 7 Patterns with Tested Examples

pytest parametrize explained with 7 tested patterns: basic cases, readable ids, stacked decorators, pytest.param with xfail and skip, indirect fixtures…

Read article →
Software Testing

Retesting vs Regression Testing: 8 Key Differences with a Real Bug Fix Example

Retesting vs regression testing explained with a real bug fix run in pytest: retesting confirmed the fix, the regression run…

Read article →
Artificial Intelligence

RAG Chunking Strategies Explained: Fixed, Overlap, Sentence, Recursive and Headings, Measured

RAG chunking strategies compared on one document with tiktoken 0.14: fixed-size, overlap, sentence packing, recursive splitting and heading-based chunks, measuring…

Read article →
DevOps

Git Stash Explained: Save, Apply, Pop and Untracked Files, Tested

Git stash explained with commands we ran on Git 2.56: push with a message, untracked files, list and show, apply…

Read article →
Test Automation

Test Doubles Explained: Dummy, Stub, Spy, Mock and Fake, with Tested Python Code

Test doubles explained with one Python example run in pytest 9.2: dummy, stub, spy, mock and fake, when to use…

Read article →