Sets: unique values and set operations

A Set is a collection of values without duplicates, and its one job is the question whether a value is in it. Adding a value that is already there changes nothing, and the order of the values is the order in which they were first added. A JavaScript array can do the same work by walking itself, which is slower and says less about the intent.

This lesson covers the eight methods, the rule that decides whether two values are the same, and the three operations of set theory written with the tools the language has: union, intersection and difference. The last section uses the same methods for a subset check, which is the shape a permission check takes.

Unique values

The constructor takes any iterable and keeps one copy of each value, so a Set around an array is the shortest way to remove duplicates. The array itself is not changed, and the values come out in the order of their first appearance.

const words = ['a', 'b', 'a', 'c', 'b']; const unique = new Set(words); console.log('the set:', [...unique].join(',')); console.log('size:', unique.size); console.log('the array is unchanged:', words.length); console.log('back to an array:', Array.from(unique).join(',')); console.log('duplicates removed:', [...new Set([1, 2, 2, 3])].join(','));

node unique.js

the set: a,b,c
size: 3
the array is unchanged: 5
back to an array: a,b,c
duplicates removed: 1,2,3

Five items became three values, and the original array still has its five positions, so the Set is a new collection and not a view of the array. The spread and Array.from both walk the set and give an array in the same order, which is the usual way back, since JSON has no form for a set. A set of numbers or of strings is the common case; an object in a set is one object and not one value of a kind, as the next section shows.

has, add and delete

has answers whether a value is in the set, add puts one in and returns the set, delete removes one and reports whether it was there. Two values are the same when they are the same value with the exception of NaN, which counts as equal to itself, and two objects are the same only when they are the same object.

const tags = new Set(['js', 'node']); console.log('has:', tags.has('js'), tags.has('rust')); console.log('add returns the set:', tags.add('eslint') === tags, tags.size); console.log('delete:', tags.delete('js'), tags.delete('js')); console.log('NaN is found by a Set:', new Set([NaN]).has(NaN)); const ada = { id: 1 }; const lookAlike = { id: 1 }; const objects = new Set([ada]); console.log('an object is found by identity:', objects.has(ada), objects.has(lookAlike)); console.log('two look-alike arrays are two values:', new Set([[1], [1]]).size);

node membership.js

has: true false
add returns the set: true 3
delete: true false
NaN is found by a Set: true
an object is found by identity: true false
two look-alike arrays are two values: 2

The three questions have three answers and no surprises, because the values are strings. NaN is the exception that makes a Set more useful than indexOf, which never finds it. The objects are the case to remember: the set holds the object ada, and a second object with the same field is a different value, so a set is not a list of equal records but a list of values, and two arrays with the same contents are two values.

Union, intersection and difference

The three operations are written with the spread and filter, and each one returns a new set: a union takes every value of both, an intersection keeps the values of the first set that the second also has, and a difference keeps the values of the first that the second does not. has inside the callback does the work, so the cost stays close to the number of values instead of their product.

const a = new Set([1, 2, 3]); const b = new Set([3, 4]); const union = new Set([...a, ...b]); const intersection = new Set([...a].filter((value) => b.has(value))); const difference = new Set([...a].filter((value) => !b.has(value))); console.log('union:', [...union].join(',')); console.log('intersection:', [...intersection].join(',')); console.log('difference a minus b:', [...difference].join(',')); console.log('difference b minus a:', [...b].filter((value) => !a.has(value)).join(','));

node operations.js

union: 1,2,3,4
intersection: 3
difference a minus b: 1,2
difference b minus a: 4

The union kept the three values of the first set and added the one that was new, in that order. The intersection found the single value both sets have, and the two differences are not each other: a minus b is 1 and 2, and b minus a is 4. Each result is a new set, so the two sources can be used again and no operation changes them.

Subsets and missing values

A subset check asks whether every value of one set is in another, which is every over the values of the first with has on the second. The program answers the question twice, once as a yes or no and once with the list of values that are missing, which is what a form shows to a user.

const isSubset = (left, right) => [...left].every((value) => right.has(value)); const required = new Set(['a', 'b']); const given = new Set(['b', 'a', 'c']); const missing = [...required].filter((value) => !given.has(value)); console.log('every required tag is present:', missing.length === 0); console.log('missing:', JSON.stringify(missing)); const small = new Set([1, 2]); const large = new Set([1, 2, 3]); console.log('subset:', isSubset(small, large), isSubset(large, small)); console.log('an empty set is a subset:', isSubset(new Set(), large)); console.log('the order of the values does not matter:', isSubset(new Set([3, 2, 1]), large));

node subset.js

every required tag is present: true
missing: []
subset: true false
an empty set is a subset: true
the order of the values does not matter: true

The two required tags are in the given set, so nothing is missing and the list is empty, which is the success value of the check. The two subset lines show that the relation has a direction: every value of the small set is in the large one and not the other way round. The empty set passes because every on nothing is true, and the last line passes because a set has no positions to compare.

Exercises

  1. Count the duplicates in [1, 1, 2, 3, 3, 3] with a Set and a subtraction. Which two numbers give the answer?
  2. Add the same object to a set twice in membership.js. What does size say and why?
  3. Write the union of three sets in one call. How many values does the result have for sets of two, two and two values with one value in all of them?
  4. Change the intersection in operations.js to a difference the other way round. Which line of the output becomes 4?
  5. Write isDisjoint(left, right), which answers whether two sets share no value, with one of the methods of this lesson.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does new Set([1, 1, 2]).size give?

    Answer

    2

    A set keeps one copy of each value, so the two ones are one value.

  2. What does new Set(["a"]).has("a") give?

    Answer

    true

    has answers a yes or no question with a boolean.

  3. What does this program print? const s = new Set([1, 2]); console.log(s.add(2).size);

    Answer

    2

    The value 2 is already in the set, so add changes nothing and returns the same set.

  4. What does this program print? const a = new Set([1, 2]); const b = new Set([2, 3]); console.log([...a].filter((v) => b.has(v)).length);

    Answer

    1

    Only the value 2 is in both sets, so the intersection has one value.

  5. How is a union of two sets written?

    Answer

    new Set([...a, ...b])

    The spread gives every value of both and the constructor removes the duplicates, while the spread alone gives an array and not a set.

  6. What is the difference of new Set([1, 2]) minus new Set([2, 3])?

    Answer

    A set with 1

    The difference keeps the values of the first set that the second does not have.

  7. What does a Set do with two different objects that have equal fields?

    Answer

    It keeps both, because objects are compared by identity

    Only the same object is the same value, so two look-alikes are two values.

  8. What does [...new Set("aab")].join("") print?

    Answer

    ab

    A string is iterable, and the set keeps one copy of each character in its first order.

  9. What does this program print? const s = new Set([1, 2, 3]); s.delete(2); console.log([...s].join(","));

    Answer

    1,3

    The delete removed the value 2 and the order of the other two did not change.

  10. Why is set.has(value) better than array.includes(value) in a loop?

    Answer

    A set answers the question without walking the whole collection

    The lookup of a set is what makes the intersection and the subset check cheap.

The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev