transformation
Array.prototype.flatMap
Maps each element with a callback, then flattens the result by one level (ES2019). Reach for it when a mapper naturally returns arrays and you want a single flat list back.
arr.flatMap(callbackFn[, thisArg]) Parameters
| Parameter | Purpose |
|---|---|
| callbackFn(element, index, array) | Function returning a value or array; arrays get flattened one level |
| thisArg | Value used as `this` inside callbackFn |
Examples
console.log([1,2,3].flatMap(n => [n, n * 2])); Logs: [1, 2, 2, 4, 3, 6]
console.log(['hello world','foo bar'].flatMap(s => s.split(' '))); Logs: ['hello', 'world', 'foo', 'bar']
console.log([1,2,3,4].flatMap(n => n % 2 ? [n] : [])); Logs: [1, 3] (return [] to filter items out)
console.log([1,2,3].flatMap(n => [[n, n]])); Logs: [[1, 1], [2, 2], [3, 3]] (only flattens one level)
Gotcha
Only flattens ONE level — nested arrays inside the returned array remain nested. Return [] from the callback as a combined map+filter pattern.
Related methods
Array.prototype.flat
Returns a new array with all sub-array elements concatenated up to the specified depth (ES2019). Reach for it to unnest arrays of arrays without a manual reduce.
Array.prototype.map
Creates a new array populated with the results of calling a callback on every element of the calling array. Reach for it whenever you want to transform each element 1-to-1 into a new value.
Array.prototype.reduce
Runs a reducer function on each element, left-to-right, folding the array into a single accumulated value. Reach for it to sum/product/group/build an object or any custom fold.
Array.prototype.sort
Sorts the array in place and returns the same array; without a compareFn elements are coerced to strings and sorted lexicographically. Reach for it when you need ordered data — but always pass a compareFn for numbers.
Array.prototype.reverse
Reverses the order of elements in place and returns the same (mutated) array. Reach for it when you truly want to reverse the source; otherwise use toReversed().