Remove Duplicates in JavaScript

Level 394 keystrokes

A Set only stores unique values. Converting back to array removes duplicates.

JavaScript code

// Define a function to get unique values
1function unique(arr) {
// new Set(arr) keeps each value only once, dropping duplicates
// [...] spreads the Set back into an array
2 return [...new Set(arr)];
3}
// Call with an array containing duplicates
// Result: [1, 2, 3, 4]
4console.log(unique([1, 2, 2, 3, 3, 3, 4]));

Output

[ 1, 2, 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.

  • ,× 6
  • .× 4
  • (× 4
  • )× 4
  • ;× 2
  • [× 2
  • ]× 2
  • {× 1
  • }× 1

More JavaScript examples at level 3

← JavaScript typing practice