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

Array.prototype.flatMap() β€” double even numbers

πŸ“– Usage Example
const nums = [1, 2, 3, 4]
nums.flatMap(n => n % 2 === 0 ? [n * 10] : [])
// β†’ [20, 40]  (filter + transform in one step)

Return an empty array from flatMap() to filter out unwanted elements while transforming.

Array.prototype.flatMap() β€” combined filter and map

flatMap() can replace a filter().map() chain. Returning an empty array [] for skipped elements and a wrapped value [result] for kept ones achieves filtering and mapping in a single pass.

Challenge: Implement doubleEvens(nums) that returns doubled even numbers, skipping odds.

doubleEvens([1, 2, 3, 4, 5]) // β†’ [4, 8]
doubleEvens([1, 3, 5])       // β†’ []
πŸ’‘ Hints (2)
  • β€’ Returning `[]` for unwanted elements effectively skips them.
  • β€’ Returning `[x * 2]` wraps the result; `flatMap` then unwraps it into the final array.