Emmanuel Akinfulubi

JavaScriptArray

flat() and flatMap() in JavaScript

Intermediate · 3 min read

Arrays inside arrays turn up all the time. Each order has a list of items, each line of text splits into a list of words, each page of results is its own list. Often you want one flat list instead: every item, every word, every result. JavaScript has two methods for this: flat, which removes the nesting, and flatMap, which changes each item and flattens in the same pass.

In this tutorial you will flatten [1, [2, [3, [4]]]] one level, two levels and all the way down. Then you will use flatMap to split lines into words, and to map and filter at the same time. You should know arrays, map, split and arrow functions.

What "depth" means

Count the brackets. In [1, [2, [3, [4]]]], the 1 sits at the top level. The 2 is one level down, inside one extra pair of brackets. The 3 is two levels down, and the 4 is three levels down. Flattening by one level removes one pair of inner brackets everywhere.

Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.

18 flat and flatMap

fair

Flatten [1, [2, [3, [4]]]] by one level, by two, and completely. Then use flatMap to map and filter in one pass.

Stuck? Three hints, smallest first
  1. 1. flat() defaults to a depth of 1. flat(Infinity) goes all the way down.
  2. 2. flatMap(f) is map(f).flat() — one level of flattening, no more.
  3. 3. Returning [] from a flatMap callback removes that element; returning two values duplicates it.

Step 1: flat() removes one level

Step 1

const nested = [1, [2, [3, [4]]]];
console.log(JSON.stringify(nested.flat())); // [1,2,[3,[4]]]

JSON.stringify just prints the whole structure on one line so you can see every bracket. With no argument, flat goes one level deep. The 2 came up to the top; the 3 and 4 are still nested.

Step 2: choose a depth

Give flat a number to remove more levels. Infinity means "keep going until nothing is nested".

Step 2

const nested = [1, [2, [3, [4]]]];
console.log(JSON.stringify(nested.flat(2)));        // [1,2,3,[4]]
console.log(JSON.stringify(nested.flat(Infinity))); // [1,2,3,4]

flat returns a new array, so nested is never changed.

Step 3: flat drops holes

An array can have holes, empty slots where nothing is stored. You make one by leaving a gap between two commas. flat skips them.

Step 3

console.log([1, , 3].length); // 3
console.log([1, , 3].flat()); // [ 1, 3 ]

Step 4: map, then flat

Now say you have lines of text and want every word. map with split gives you an array per line:

Step 4

const words = ['the lagos bus', 'is late'];
const perLine = words.map((line) => line.split(' '));
console.log(JSON.stringify(perLine)); // [["the","lagos","bus"],["is","late"]]
console.log(perLine.flat());          // [ 'the', 'lagos', 'bus', 'is', 'late' ]

That is a list of lists. Adding .flat() gives the flat list of words.

Step 5: flatMap does both

flatMap(fn) is exactly map(fn).flat(), in one method and one pass.

Step 5

const words = ['the lagos bus', 'is late'];
const allWords = words.flatMap((line) => line.split(' '));
console.log(allWords); // [ 'the', 'lagos', 'bus', 'is', 'late' ]

Step 6: zero, one or many per item

Here is the clever part. Because your function returns an array, each item can turn into any number of items. Return [] and the item disappears. Return two values and it becomes two.

Step 6

const oddsOnly = [1, 2, 3, 4].flatMap((n) => (n % 2 ? [n] : []));
console.log(oddsOnly);  // [ 1, 3 ]
const doubledUp = [1, 2].flatMap((n) => [n, n * 10]);
console.log(doubledUp); // [ 1, 10, 2, 20 ]

n % 2 is the remainder after dividing by 2: 1 for odd numbers, which counts as true, and 0 for even, which counts as false. So odd numbers return [n] and stay, even numbers return [] and vanish. That is a filter done inside a map.

Step 7: one level only

flatMap only flattens one level, and a plain value that isn't an array is kept as it is.

Step 7

console.log(JSON.stringify([1].flatMap((n) => [[n]]))); // [[1]]
console.log([1, 2].flatMap((n) => n));                  // [ 1, 2 ]

Returning [[n]] leaves one pair of brackets behind. If you need deeper flattening, use map and then flat(2) or flat(Infinity).

The full solution

The panel flattens the nested array at three depths, then uses flatMap to split words, keep only the odd numbers and double up a list. Press Run to see each result.

The answer

const nested = [1, [2, [3, [4]]]];

const words = ['the lagos bus', 'is late'];
const allWords = words.flatMap((line) => line.split(' '));

// Returning [] drops an element; returning several expands it.
const oddsOnly = [1, 2, 3, 4].flatMap((n) => (n % 2 ? [n] : []));
const doubledUp = [1, 2].flatMap((n) => [n, n * 10]);

console.log('flat()        :', nested.flat());
console.log('flat(2)       :', nested.flat(2));
console.log('flat(Infinity):', nested.flat(Infinity));
console.log('holes go too  :', [1, , 3].flat(), '<- the middle slot was a hole');
console.log('words         :', allWords);
console.log('odds only     :', oddsOnly);
console.log('doubled up    :', doubledUp);

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('flat() removes one level', nested.flat(), [1, 2, [3, [4]]]);
test('a depth argument removes more', nested.flat(2), [1, 2, 3, [4]]);
test('Infinity flattens completely', nested.flat(Infinity), [1, 2, 3, 4]);
test('flat also drops holes', [1, , 3].flat(), [1, 3]);
test('flatMap maps then flattens one level', allWords, ['the', 'lagos', 'bus', 'is', 'late']);
test('returning [] removes the element', oddsOnly, [1, 3]);
test('returning two values expands it', doubledUp, [1, 10, 2, 20]);
test('flatMap flattens one level only', [1].flatMap((n) => [[n]]), [[1]]);
test('a non-array return is kept as it is', [1, 2].flatMap((n) => n), [1, 2]);

Also Basic 35, which flattens by hand with recursion. The angle here is the built-in and its depth argument: flat() is one level, and the recursive hand-written version is only needed when you want to stop at a computed depth or flatten something that is not an array.

flatMap is the one to internalise. Because the callback returns an array, it can produce zero, one or many elements per input — which makes it a filter and a map at the same time, in a single pass. map(...).filter(Boolean) is two passes and mishandles a legitimate falsy result.

Common mistakes

  • Expecting flat() to flatten everything. It goes one level by default. Use flat(Infinity) for all levels.
  • Returning nested arrays from flatMap. It only removes one level, so [[n]] stays nested.
  • Using map(...).filter(Boolean) to map and drop. That is two passes, and it throws away real results like 0. With flatMap you choose exactly what to drop by returning [].

Try it yourself

  1. Flatten [[1, 2], [3], [], [4, 5]] into one array.
  2. Given orders like { items: ['rice', 'beans'] }, get every item from every order with flatMap.
  3. Use flatMap to turn ['a', 'b'] into ['a', 'a', 'b', 'b'].

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.