Unique Values with Set in JavaScript

Level 4229 keystrokes

Builds a Set from an array with duplicates, which keeps only 1, 2, 3 and 4, spreads it back into an array, and prints the Set, the array, has(3) (true) and size (4).

JavaScript code

// An array of 10 numbers with many duplicates
1const numbers = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4];
// A Set stores each value only once, so it keeps 1, 2, 3, 4 in insertion order
2const uniqueSet = new Set(numbers);
// The spread syntax turns the Set back into an array
3const uniqueArray = [...uniqueSet];
// Prints the Set itself: Set(4) { 1, 2, 3, 4 }
4console.log(uniqueSet);
// Prints the array of unique values: [ 1, 2, 3, 4 ]
5console.log(uniqueArray);
// has checks whether a value is in the Set; 3 is, so this prints true
6console.log(uniqueSet.has(3));
// size is the number of unique values: 4
7console.log(uniqueSet.size);

Output

Set(4) { 1, 2, 3, 4 }
[ 1, 2, 3, 4 ]
true
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.

  • ,× 9
  • .× 9
  • ;× 7
  • (× 6
  • )× 6
  • =× 3
  • [× 2
  • ]× 2

More JavaScript examples at level 4

← JavaScript typing practice