Set Data Structure in JavaScript

Level 4233 keystrokes

Uses Set to store unique values and demonstrates add, delete, has, and size operations.

JavaScript code

// Create an array with duplicate values
1const nums = [1, 2, 2, 3, 3, 3, 4, 5, 5];
// Set automatically removes duplicates
2const uniqueSet = new Set(nums);
3
// size property returns the number of unique elements
4console.log(uniqueSet.size);
// has() checks if a value exists in the Set
5console.log(uniqueSet.has(3));
// Spread operator converts Set back to array
6console.log([...uniqueSet]);
7
// add() inserts a new value (ignored if duplicate)
8uniqueSet.add(6);
// delete() removes a value from the Set
9uniqueSet.delete(1);
// Output the modified Set as array
10console.log([...uniqueSet]);

Output

5
true
[ 1, 2, 3, 4, 5 ]
[ 2, 3, 4, 5, 6 ]
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.

  • .× 14
  • ,× 8
  • ;× 8
  • (× 8
  • )× 8
  • [× 3
  • ]× 3
  • =× 2

More JavaScript examples at level 4

← JavaScript typing practice