Array flatMap in JavaScript

Level 3149 keystrokes

Uses flatMap() to split strings and flatten the result into a single array.

JavaScript code

// Create an array of sentences
1const sentences = ["Hello World", "Good Morning"];
// flatMap() maps each sentence with s.split(" ") and flattens the result one level
// ["Hello", "World"] and ["Good", "Morning"] become one array
2const words = sentences.flatMap(s => s.split(" "));
// Output: ["Hello", "World", "Good", "Morning"]
3console.log(words);
// Prints 4, the number of words
4console.log(words.length);

Output

[ 'Hello', 'World', 'Good', 'Morning' ]
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
  • .× 5
  • ;× 4
  • (× 4
  • )× 4
  • =× 3
  • ,× 1
  • [× 1
  • ]× 1
  • >× 1

More JavaScript examples at level 3

← JavaScript typing practice