Expand or discard items
Convert each source item into zero, one, or several output items in one pass.
JavaScript · Function
Array.prototype.flatMap() maps each array element and flattens each callback result by one level. It returns a new array and does not recursively flatten deeper nesting.
Call flatMap() on an array with a callback. JavaScript invokes the callback for each present element, appends a non-array result directly, or appends the elements of an array result after flattening that result by one level; it returns a new array rather than changing the source array.
flatMap(callbackFn)
flatMap(callbackFn, thisArg)| Name | Type | Description |
|---|---|---|
callbackFn | Function | A function to execute for each element in the array. It should return an array containing new elements of the new array, or a single non-array value to be added to the new array. |
thisArg | Any | A value to use as this when executing callbackFn. |
A new array with each element being the result of the callback function and flattened by a depth of 1.
const values = [1, 2, 3];
const expanded = values.flatMap((value) => [value, value * 2]);
console.log(expanded); // [1, 2, 2, 4, 3, 6]Each callback result contributes its elements to the new array, flattened by one level.
Convert each source item into zero, one, or several output items in one pass.
Turn nested collections such as each object's list of records into one flat result.
Keep only matching values by returning an empty array for nonmatches.
flatMap() applies a callback to each present array element and flattens each returned array by one level into a new array. It is equivalent in behavior to map() followed by flat(1), with the combined operation generally being more efficient.
Follow-up: What happens when the callback returns a string or Set? They are appended as single values because only returned arrays are flattened.
The callback receives the current element, its index, and the source array, as with map(). A returned array contributes its elements; a non-array return value contributes one element.
Follow-up: Does changing the source array during iteration change the number of callback invocations? No: flatMap() reads the initial length and visits integer-indexed properties below that length.
flatMap() is generic: its this value needs a length property and integer-keyed properties. The callback's result is flattened only when that result is an Array.
Follow-up: Can it flatten a custom iterable? No. A custom iterable is appended as one value unless it is itself an Array.
Array.prototype.map()Array.prototype.flat()Array.prototype.filter()Array.prototype.forEach()