Set Operations in JavaScript

Level 4237 keystrokes

Set operations like union and intersection can be performed using spread and filter.

JavaScript code

// Create two Sets with some overlapping values
1const setA = new Set([1, 2, 3, 4]);
2const setB = new Set([3, 4, 5, 6]);
// Union: combine both sets (duplicates removed automatically)
// Spread both sets into a new Set
3const union = new Set([...setA, ...setB]);
// Intersection: elements that exist in both sets
// Filter setA to keep only elements that setB has
4const intersection = new Set([...setA].filter(x => setB.has(x)));
// Print union: [1, 2, 3, 4, 5, 6]
5console.log([...union]);
// Print intersection: [3, 4]
6console.log([...intersection]);

Output

[ 1, 2, 3, 4, 5, 6 ]
[ 3, 4 ]
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this JavaScript code and how often they appear.

  • .× 19
  • (× 8
  • )× 8
  • ,× 7
  • ;× 6
  • [× 6
  • ]× 6
  • =× 5
  • >× 1

More JavaScript examples at level 4

← JavaScript typing practice