Array.prototype.flatMapLoading saved progress…

Array.prototype.flatMap

Array.prototype.flatMap maps each element to a value — often an array — and then flattens the result by one level, in a single pass. It's the tool for "each input produces zero, one, or many outputs": splitting sentences into words, expanding a row into several, or dropping some inputs entirely.

Implement arrayFlatMap(arr, callback, thisArg). Call callback on each element; if it returns an array, its items are spliced into the result (flattened one level); if it returns a non-array, that value is pushed as-is. The result is a new array.

Signature

function arrayFlatMap(arr, callback, thisArg) {
  // callback: (value, index, array) => mappedValueOrArray
  // returns a new array, flattened one level.
}

Examples

arrayFlatMap([1, 2, 3], (x) => [x, x * 2]); // [1, 2, 2, 4, 3, 6]
arrayFlatMap([1, 2, 3], (x) => x * 10);     // [10, 20, 30]  — non-array pushed as-is
// Returning [] drops the element; returning many expands it:
arrayFlatMap([1, 2, 3, 4], (x) => (x % 2 === 0 ? [x] : [])); // [2, 4]
arrayFlatMap([1, 2], (x) => [[x]]); // [[1], [2]]  — only ONE level flattened

Notes

  • One level only — a callback returning [[x]] leaves the inner array nested. flatMap never flattens deeply.
  • Non-arrays pass through — if the callback returns a plain value, it's added directly (not wrapped).
  • [] acts as a filter — returning an empty array contributes nothing, so flatMap can drop elements as well as expand them.
  • Skips holes — like map, holes in a sparse array are not visited.
  • New array — return a fresh array; don't mutate the input. Predicate args are (value, index, array).
Loading editor…