The JavaScript array.flatMap() method
The flatMap() method maps each element with a callback and then flattens the result by one level — equivalent to map() followed by flat(), but in one pass. It's handy when a map callback returns arrays you want merged, or for expanding and filtering at the same time.
Overview
flatMap() combines two steps: it runs a map() over each element, then flattens the result one level. So arr.flatMap(fn) is exactly arr.map(fn).flat(), just more efficient and more readable. It shines when your callback naturally returns an array per element and you want all those arrays merged into one flat result.
A classic example is splitting: sentences.flatMap(s => s.split(" ")) turns an array of sentences into a single flat array of words, because each split() produces an array that flatMap() then merges. Without it you'd get an array of arrays and need a separate flatten.
There's a clever bonus: because it flattens, returning an empty array [] from the callback drops that element entirely, and returning [value] keeps it — so flatMap() can map and filter in one go. Note it only flattens a single level; for deeper nesting use flat() with a depth.
Syntax
array.flatMap(callbackFn)
[1, 2, 3].flatMap(n => [n, n * 2]) // [1, 2, 2, 4, 3, 6]
["a b", "c d"].flatMap(s => s.split(" ")) // ["a", "b", "c", "d"]
// map + filter: [] drops, [x] keeps
nums.flatMap(n => n > 0 ? [n] : [])
Parameters
The array.flatMap() method accepts the following parameters.
| Parameter | Description |
|---|---|
callbackFn |
Run on each element; its return value is flattened one level into the result. Receives (element, index, array). |
thisArg |
Optional. A value to use as this inside the callback. |
Example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
const lines = ['the quick', 'brown fox'];
const words = lines.flatMap(line => line.split(' '));
document.getElementById('out').textContent =
'words (' + words.length + '): ' + words.join(', ');
// words (4): the, quick, brown, fox
</script>
Best practices
- Use it when a map callback returns arrays you want merged — cleaner than
map().flat(). - Expand items (one to many) by returning an array per element.
- Map and filter in one pass: return
[]to drop an element,[value]to keep it. - It only flattens one level — use flat() with a depth for deeper nesting.
Frequently asked questions
What does flatMap() do?
map().flat() in a single call.What is the difference between map() and flatMap()?
flatMap() flattens one level, so callbacks that return arrays get merged.Can flatMap() filter elements?
[] to drop an element and [value] to keep it, mapping and filtering together.