Skip to content

Array FlatMap Method

flatMap() calls a function on each element, as map() does, and then flattens the result by one level, as flat() does. It gives the same result as map(fn).flat(), in one pass. Use it when each element should turn into a list of values and you want one combined list at the end.

const lines = ['good morning', 'see you soon'];
console.log(lines.map((line) => line.split(' ')));
console.log(lines.flatMap((line) => line.split(' ')));

This prints:

[ [ 'good', 'morning' ], [ 'see', 'you', 'soon' ] ]
[ 'good', 'morning', 'see', 'you', 'soon' ]

Because the callback’s result is flattened, returning an empty array removes the element, and returning an array of one value keeps it. That lets flatMap() filter and transform in a single pass. Here only the entries that are numbers survive, converted to numbers:

const entries = ['3', 'n/a', '7', '', '12'];
const numbers = entries.flatMap((entry) => {
const value = Number.parseInt(entry, 10);
return Number.isNaN(value) ? [] : [value];
});
console.log(numbers);

This prints:

[ 3, 7, 12 ]

The same callback can also return several values for one element, which is useful for expanding records. Each order below becomes one line per item:

const orders = [
{ customer: 'Asha', items: ['kettle', 'mugs'] },
{ customer: 'Tom', items: ['toaster'] },
];
console.log(orders.flatMap((order) => order.items.map((item) => `${order.customer}: ${item}`)));
console.log([1, 2].flatMap((n) => [[n, n * 10]]));

This prints:

[ 'Asha: kettle', 'Asha: mugs', 'Tom: toaster' ]
[ [ 1, 10 ], [ 2, 20 ] ]

The second line shows the limit: flatMap() flattens only one level, so an array returned inside another array stays an array. Unlike flat(), it takes no depth argument. For deeper nesting, call map() and then flat() with the depth you need.

Steve Griffith covers this topic in his video Understanding Array flatMap.