JS Built-ins
← Array93 / 226
ArrayArray.prototype.flatMapintermediate

Array.prototype.flatMap() β€” split sentences into words

πŸ“– Usage Example
const sentences = ['hello world', 'foo bar']
sentences.flatMap(s => s.split(' '))
// β†’ ['hello', 'world', 'foo', 'bar']

Use flatMap() to split each string and collect all words into a single flat array.

Array.prototype.flatMap() β€” string splitting

flatMap() is perfect for transforming each element into multiple values and collecting them all into a flat array.

Challenge: Implement splitWords(sentences) that splits each sentence into words and returns all words in a single flat array.

splitWords(['hello world', 'foo bar baz']) // β†’ ['hello', 'world', 'foo', 'bar', 'baz']
splitWords(['one'])                         // β†’ ['one']
πŸ’‘ Hints (2)
  • β€’ `s.split(' ')` splits a sentence into an array of words.
  • β€’ `flatMap` then flattens all those word-arrays into a single flat array.