JS Built-ins
← Array92 / 226
ArrayArray.prototype.flatMapbeginner

Array.prototype.flatMap() β€” duplicate each element

πŸ“– Usage Example
const nums = [1, 2, 3]
nums.flatMap(n => [n, n])  // β†’ [1, 1, 2, 2, 3, 3]

Use flatMap() to map each element to an array and flatten the results by one level.

Array.prototype.flatMap()

Array.prototype.flatMap(callback) maps each element using a callback and then flattens the result by one level. It is equivalent to arr.map(fn).flat(1) but slightly more efficient.

Challenge: Implement duplicateEach(arr) that returns a new array where each element appears twice, using flatMap(x => [x, x]).

duplicateEach([1, 2, 3]) // β†’ [1, 1, 2, 2, 3, 3]
duplicateEach([])        // β†’ []
πŸ’‘ Hints (2)
  • β€’ `flatMap(x => [x, x])` returns `[x, x]` for each element, which are then flattened into the result.
  • β€’ The flattening is exactly one level deep β€” nested arrays inside the returned arrays are not unwrapped further.