Array flatMap in JavaScript

Level 3144 keystrokes

flatMap() maps each element then flattens the result by one level.

JavaScript code

// Create an array of sentence strings
1const sentences = ["hello world", "foo bar"];
// flatMap() splits each sentence into words, then flattens one level
// It is the same as map() followed by flat(1)
2const words = sentences.flatMap(s => s.split(" "));
// Print the flattened array of words
// ["hello", "world", "foo", "bar"]
3console.log(words);
// Print the total word count: 4
4console.log(words.length);

Output

[ 'hello', 'world', 'foo', 'bar' ]
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