JS Built-ins
← Array96 / 226
ArrayArray.prototype.flatMapadvanced

Array.prototype.flatMap() β€” compact strings

πŸ“– Usage Example
const strs = ['hello', '', 'world', '']
strs.flatMap(s => s ? [s.trim()] : [])
// β†’ ['hello', 'world']

Use flatMap() to simultaneously trim, filter out empty strings, and flatten results.

Array.prototype.flatMap() β€” trim and filter

flatMap() can both transform and filter in one pass. Trimming strings and removing empty ones is a clean use case.

Challenge: Implement compactMap(arr) that trims each string and removes empty strings using flatMap.

compactMap(['  hello  ', '', '  world  ', '   ']) // β†’ ['hello', 'world']
compactMap(['', '  '])                             // β†’ []
πŸ’‘ Hints (2)
  • β€’ `s.trim()` removes leading/trailing whitespace.
  • β€’ Return `[trimmed]` to keep or `[]` to discard β€” `flatMap` handles the flattening.