Skip to content
jshacks.dev
Fundamentals

JavaScript Array flatMap Method vs map Followed by flat

Array flatMap() maps and flattens one level in a single pass, which also lets one callback drop, keep or expand each item. See where it beats map then flat.

7 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, npm, Node.js, Vite and TypeScript logos.

Some transformations produce zero, one or several outputs for each input: splitting sentences into words, expanding an order into its lines, keeping only the valid rows and reshaping them. With map() those need a second pass to flatten or filter the result. Array.prototype.flatMap() is the one-pass answer, and the part that surprises people is the flattening depth, which is exactly one and cannot be changed. This post covers the behavior on Node.js 24, the filter-and-map idiom, and the places it misleads. The wider family of array methods is in the complete guide to modern JavaScript.

The simplest case splits strings.

JavaScript
const sentences = ["map then flat", "one pass", ""];

const words = sentences.flatMap((sentence) => sentence.split(" "));

console.log(words);
console.log(sentences.map((sentence) => sentence.split(" ")));
Text
[ 'map', 'then', 'flat', 'one', 'pass', '' ]
[ [ 'map', 'then', 'flat' ], [ 'one', 'pass' ], [ '' ] ]

The second line shows what map() alone returns, an array of arrays, and the first is what flatMap() gives. Note the empty string: splitting "" on a space yields [""], one item holding an empty string, so it survives as a word. That is the callback's behavior and not the method's.

One level, no more

The flattening depth is fixed at one. A callback that returns an array of arrays produces a nested array in the result.

JavaScript
const result = [1, 2].flatMap((n) => [[n, n * 10]]);

console.log(result);
console.log([1, 2].map((n) => [[n, n * 10]]).flat(2));
Text
[ [ 1, 10 ], [ 2, 20 ] ]
[ 1, 10, 2, 20 ]

The callback returned [[n, n * 10]], an array holding an array, and flatMap() opened the outer layer only. If you need deeper flattening, split the work: map() then flat(depth), as covered in the flat() post. A callback that returns pairs and expects a flat list is the typical way to trip over this.

A return value that is not an array is kept as one item.

JavaScript
const mixed = [1, 2, 3].flatMap((n) => (n === 2 ? [n, n] : n));

console.log(mixed);
Text
[ 1, 2, 2, 3 ]

Arrays are opened and scalars are appended, the same rule concat() follows. Returning a mix is legal and usually a sign that the callback should always return an array, which is easier to read.

Filtering and mapping in one pass

Returning an empty array removes an item, and returning a one item array keeps it. That makes flatMap() a filter and a map at once.

JavaScript
const inputs = ["12", "abc", "7", "", "40"];

const numbers = inputs.flatMap((text) => {
  const value = Number(text);
  return text !== "" && !Number.isNaN(value) ? [value] : [];
});

console.log(numbers);
console.log(inputs.map(Number).filter((n) => !Number.isNaN(n)));
Text
[ 12, 7, 40 ]
[ 12, 7, 0, 40 ]

The second line is the naive two-step version, and it keeps a 0 for the empty string because Number("") is 0, not NaN. The one-pass version made the decision where the text was still available. That is the real advantage of flatMap() for this shape: the check and the conversion share one scope, so the information needed to reject an item has not been thrown away by the time the filter runs.

We use the idiom for parse-and-validate steps and avoid it for plain filtering. filter() followed by map() reads better when the test and the transform are separate ideas, and the second pass costs little for ordinary list sizes. If a team finds the empty array return obscure, a named helper makes the intent visible.

JavaScript
const keep = (value) => [value];
const drop = [];

const evens = [1, 2, 3, 4, 5, 6].flatMap((n) => (n % 2 === 0 ? keep(n * n) : drop));

console.log(evens);
Text
[ 4, 16, 36 ]

The shared drop array is safe because flatMap() only reads it, and it saves an allocation per dropped item.

Expanding records

Another strong use is expanding each record into several, such as orders into lines or a post into one row per tag.

JavaScript
const posts = [
  { title: "Closures", tags: ["scope", "functions"] },
  { title: "Promises", tags: ["async"] },
  { title: "Draft", tags: [] },
];

const rows = posts.flatMap((post) => post.tags.map((tag) => ({ tag, title: post.title })));

console.log(rows);
Text
[
  { tag: 'scope', title: 'Closures' },
  { tag: 'functions', title: 'Closures' },
  { tag: 'async', title: 'Promises' }
]

The post with no tags produced nothing, which is correct: it has no rows. A map() here would have returned an empty array for it and left a nested structure to flatten. The callback also shows the pattern of a map() inside a flatMap(), which is common and reads naturally: for each post, map its tags to rows.

An async callback gives promises

An async function returns a promise, and a promise is an object, not an array, so flatMap() keeps it as an item.

JavaScript
const result = [1, 2].flatMap(async (n) => [n, n]);

console.log(result);
console.log((await Promise.all(result)).flat());
Text
[ Promise { [ 1, 1 ] }, Promise { [ 2, 2 ] } ]
[ 1, 1, 2, 2 ]

The first line is an array of promises and not the flat numbers you wanted. Resolve them with Promise.all, then flatten the results with flat(). The same applies to filter() and find(), covered in the filter() post.

The callback's arguments and the index

Like map(), the callback receives (value, index, array), which makes position-aware expansions straightforward. Interleaving a separator, pairing each item with its index, or emitting a header before the first item are all single expressions.

JavaScript
const names = ["Ada", "Grace", "Linus"];

const withIndex = names.flatMap((name, index) => [index, name]);
const withSeparators = names.flatMap((name, index) =>
  index === 0 ? [name] : [",", name],
);

console.log(withIndex);
console.log(withSeparators.join(""));
Text
[ 0, 'Ada', 1, 'Grace', 2, 'Linus' ]
Ada,Grace,Linus

The separator version avoids the trailing comma that a naive loop leaves, because the first item is special-cased by its index. That is the kind of small job where flatMap() shortens a loop that would otherwise carry a mutable flag. For a join of strings, join(",") is shorter still, and the interleave shape matters when the separator is an element, such as a DOM node or a React fragment, and not a string.

How it compares with map then flat

The two spellings give the same result for depth one. The difference is allocation and reading order.

SpellingIntermediate arrayDepth
arr.map(fn).flat()Yes, the mapped arrayAny, with flat(depth)
arr.flatMap(fn)NoExactly 1

For arrays of a few thousand items, nobody can see the difference. We pick on readability: flatMap() when the callback naturally returns a list, map().flat() when flattening is a separate step you want visible, or when the depth is more than one.

Array-likes and Sets are not flattened

The rule matches flat(): only real arrays are opened.

JavaScript
const result = [1].flatMap(() => new Set([2, 3]));

console.log(result);
console.log([1].flatMap(() => [...new Set([2, 3])]));
Text
[ Set(2) { 2, 3 } ]
[ 2, 3 ]

Spread the set into an array inside the callback to flatten it.

Pinning the filter and map behavior with a test

The filter-and-map idiom hides a decision in the callback, and a decision with no test is one a later edit changes without noticing. The cases worth pinning are the ones where a naive rewrite goes wrong: an item that should drop, an item that should expand and an input that is empty.

JavaScript
import { test } from "node:test";
import assert from "node:assert/strict";

const parseAll = (inputs) =>
  inputs.flatMap((text) => {
    const value = Number(text);
    return text !== "" && !Number.isNaN(value) ? [value] : [];
  });

test("keeps valid numbers and drops the rest", () => {
  assert.deepEqual(parseAll(["12", "abc", "", "7"]), [12, 7]);
});

test("returns an empty list for no input", () => {
  assert.deepEqual(parseAll([]), []);
});

test("keeps a real zero", () => {
  assert.deepEqual(parseAll(["0"]), [0]);
});

Run it with node --test on Node.js 24. The third test is the one that matters: a rewrite to filter(Boolean) would drop a legitimate 0, the same trap described in the filter() post, and the test fails the moment someone makes that tidy-up.

Keeping the validation inside the callback also means the error handling has one home. If you later need to report which inputs were rejected, the callback is the only place that knows, and you can collect them there instead of recomputing the check in a separate pass.

When flatMap is the wrong tool

Reach for flatMap() when each input maps to a variable number of outputs. If every input maps to exactly one output, map() is clearer. If you only drop items, filter() says so. If you need more than one level of flattening, use map() followed by flat(depth).

For very large inputs that you transform lazily and may abandon early, iterator helpers on Node.js 22 and later include their own flatMap() that works item by item without building an array.

The method is specified in Array.prototype.flatMap, and MDN's page for flatMap lists the support and the callback parameters.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.