FrontendDeveloper.in

ECMAScript question detail

Set Methods

ES2025 introduces several new methods to the Set prototype that make working with sets more convenient and expressive. These methods provide operations commonly found in set theory, such as union, intersection, and difference.

// Create some sample sets
const set1 = new Set([1, 2, 3, 4, 5]);
const set2 = new Set([3, 4, 5, 6, 7]);

// Union - combines elements from both sets
const union = set1.union(set2);
console.log([...union]); // [1, 2, 3, 4, 5, 6, 7]

// Intersection - elements present in both sets
const intersection = set1.intersection(set2);
console.log([...intersection]); // [3, 4, 5]

// Difference - elements in first set but not in second
const difference = set1.difference(set2);
console.log([...difference]); // [1, 2]

// Symmetric Difference - elements in either set but not in both
const symDifference = set1.symmetricDifference(set2);
console.log([...symDifference]); // [1, 2, 6, 7]

The new Set methods include:

  1. Set.prototype.union(): Returns a new Set containing all elements from both sets.
  2. Set.prototype.intersection(): Returns a new Set containing elements present in all sets.
  3. Set.prototype.difference(): Returns a new Set containing elements present in the first set but not in the second.
  4. Set.prototype.symmetricDifference(): Returns a new Set containing elements present in either set but not in both.
  5. Set.prototype.isSubsetOf(): Returns a boolean indicating if the set is a subset of the given set.
  6. Set.prototype.isSupersetOf(): Returns a boolean indicating if the set is a superset of the given set.
  7. Set.prototype.isDisjointFrom(): Returns a boolean indicating if the set has no elements in common with the given set.

These methods can be particularly useful for data processing, filtering, and comparison operations.

// Practical example: Finding common interests between users
const user1Interests = new Set(["coding", "reading", "music", "hiking"]);
const user2Interests = new Set(["gaming", "music", "movies", "hiking"]);

// Find common interests
const commonInterests = user1Interests.intersection(user2Interests);
console.log([...commonInterests]); // ["music", "hiking"]

// Find unique interests of user1
const uniqueInterests = user1Interests.difference(user2Interests);
console.log([...uniqueInterests]); // ["coding", "reading"]
Back to all ECMAScript questions
Get LinkedIn Premium at Rs 399