Flatten array JavaScript: flat, flat(Infinity), flatMap, concat, reduce

How to flatten an array in JavaScript: flatten array javascript, js flatten array, javascript flatten array with flat(), depth and Infinity, flatMap vs map+flat(1), recursive concat/reduce for legacy engines, non-array elements, and sparse array caveats. Snippets include short expected-output notes from Node runs.

Published

Updated

Read time 4 min read

Reviewed byDeepak Prasad

Flatten array JavaScript: flat, flat(Infinity), flatMap, concat, reduce

Javascript flatten array and js flatten array usually mean turning nested arrays into a single list of values. In modern JavaScript, Array.prototype.flat (ES2019) is the standard array flat javascript tool: it returns a new array and only unwraps elements that are Array instances. For map plus one-level flatten, use flatMap. Older stacks may still use recursion with concat or reduce—the same idea as how to flatten an array in javascript tutorials before flat existed. For building nested structures first, see JavaScript array fill and add to an array.

Tested on: Node.js v20.18.2. A short note after each snippet describes what you should see in the console.


Quick reference

flat / flatMap return new arrays—choose depth, Infinity, or a legacy reducer based on engine support and how deep nesting can grow.

Need Use
One level arr.flat() or arr.flat(1)
All levels arr.flat(Infinity)
Map + flatten 1 level arr.flatMap(fn)
Legacy / no ES2019 Recursive concat / reduce

flat() — default depth 1 (flatten array js)

Default depth is 1: only the outermost nested arrays are opened.

javascript
const nestedArray = [1, [2, [3, 4], 5], 6];
console.log(nestedArray.flat());
Output

You should see one line like: [ 1, 2, [ 3, 4 ], 5, 6 ].


flat(Infinity) — fully flatten (how to flatten an array in javascript)

Infinity means keep flattening until no nested Array values remain.

javascript
const nestedArray = [1, [2, [3, 4], 5], 6];
console.log(nestedArray.flat(Infinity));
Output

You should see one line like: [ 1, 2, 3, 4, 5, 6 ].


flat(depth) — specific depth (js array flatten control)

Pass a numeric depth to flatten exactly that many levels.

javascript
console.log([1, [2, [3, [4]]]].flat(2));
Output

You should see one line like: [ 1, 2, 3, [ 4 ] ].

Two levels are flattened; one nested [4] remains.


flatMap — map then flatten one level (flat array js)

Equivalent to map(...).flat(1), but in one method:

javascript
console.log([1, 2, 3].flatMap((x) => [x, x * 2]));
Output

You should see one line like: [ 1, 2, 2, 4, 3, 6 ].


Recursive concat loop (flattening an array without flat)

Useful where flat is unavailable; watch stack depth on extremely deep trees.

javascript
function flattenArray(arr) {
  let flattened = [];
  for (let i = 0; i < arr.length; i++) {
    if (Array.isArray(arr[i])) {
      flattened = flattened.concat(flattenArray(arr[i]));
    } else {
      flattened.push(arr[i]);
    }
  }
  return flattened;
}

const nestedArray = [1, [2, [3, 4], 5], 6];
console.log(flattenArray(nestedArray));
Output

You should see one line like: [ 1, 2, 3, 4, 5, 6 ].


Recursive reduce + concat

Another recursive style; prefer flat(Infinity) when the runtime supports it.

javascript
function flattenArray(arr) {
  return arr.reduce(
    (acc, val) =>
      Array.isArray(val) ? acc.concat(flattenArray(val)) : acc.concat(val),
    []
  );
}

const nestedArray = [1, [2, [3, 4], 5], 6];
console.log(flattenArray(nestedArray));
Output

You should see one line like: [ 1, 2, 3, 4, 5, 6 ].


Non-array elements and sparse arrays

flat does not unwrap arbitrary objects—only Array instances:

javascript
console.log([1, 2, { a: 3 }].flat());
Output

You should see one line like: [ 1, 2, { a: 3 } ].

Sparse roots interact with flat in subtle ways; one illustration:

javascript
console.log([1, , [3, , 4]].flat());
Output

You should see one line like: [ 1, 3, 4 ].

If you must preserve holes, avoid pipelines that mix flat with sparse data unless you normalize first.


Summary

Modern code starts with flat / flatMap; keep recursive concat in your pocket for pre-ES2019 environments and remember only real Array elements unwrap.

  • flat() defaults to depth 1; use flat(Infinity) for arbitrary nesting.
  • flatMap is map plus one-level flatten in one pass.
  • Recursive concat/reduce patterns cover legacy environments without flat.
  • Only real arrays flatten; plain objects and sparse holes need explicit handling.

References

MDN references for flat, flatMap, and classic helpers used in flatten array js recipes.


Frequently Asked Questions

1. Does flat mutate the original array for javascript flatten array code?

No. flat and flatMap return a new array (a shallow copy of structure). The original nested arrays are left unchanged.

2. What is the default depth of Array.prototype.flat?

  1. Only one level of nested arrays is unwrapped unless you pass a higher number or Infinity.

3. When should I use flatMap instead of map then flat?

When you want map followed by a one-level flatten. flatMap is equivalent to map then flat(1) and is slightly more efficient and clearer.

4. How do I flatten an array in javascript of unknown nesting depth?

Use nestedArray.flat(Infinity) in modern engines. In very old environments without flat, use a recursive helper that concatenates arrays.

5. Does flat unwrap plain objects that look like arrays?

No. flat only flattens elements that are arrays. Other values, including plain objects, are copied into the result as-is.

6. What happens to empty slots in a sparse array when I call flat?

flat can remove some empty slots depending on depth and structure; always inspect results if you rely on holes. Prefer dense arrays when possible.
Olorunfemi Akinlua

Boasting over five years of experience in JavaScript, specializing in technical content writing and UX design. With a keen focus on programming languages, he crafts compelling content and designs …