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

← All JS array methods · TypeScript vs JavaScript