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.
function arrayFlatMap(arr, callback, thisArg) {
// callback: (value, index, array) => mappedValueOrArray
// returns a new array, flattened one level.
}
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
[[x]] leaves the inner array nested. flatMap never flattens deeply.[] acts as a filter — returning an empty array contributes nothing, so flatMap can drop elements as well as expand them.map, holes in a sparse array are not visited.(value, index, array).