Skip to main content

Flat array from a multidimensional array

Example:

javascript
const arr = [1, [2, 3], [4, [5, 6]]];

We want to get -> [1, 2, 3, 4, 5, 6]


1. The simplest way - .flat() (ES2019+)

javascript
const flattened = arr.flat(); console.log(flattened); // [1, 2, 3, 4, [5, 6]]

By default flat() "flattens" only one level of nesting.


2. Specify the flattening depth

javascript
const deeplyFlattened = arr.flat(2); console.log(deeplyFlattened); // [1, 2, 3, 4, 5, 6]
  • flat(1) -> one level
  • flat(2) -> two levels
  • flat(Infinity) -> completely, regardless of depth

Example:

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

This is the most convenient and modern way to "flatten" an array.


3. Alternative - recursion (the old way, before flat)

javascript
function flatten(arr) { return arr.reduce( (acc, val) => acc.concat(Array.isArray(val) ? flatten(val) : val), [] ); } console.log(flatten([1, [2, [3, 4]], 5])); // [1, 2, 3, 4, 5]
  • We check each element: if it's an array -> call flatten recursively.
  • If not -> add it to the result.

4. Via toString() (only for numbers/strings)

javascript
[1, [2, [3, 4]]].toString().split(','); // ["1", "2", "3", "4"]

Works only if there are no objects or null, because everything is turned into strings.


5. Via flatMap() (for combining + flatten)

javascript
const arr = [1, 2, [3, 4]]; const result = arr.flatMap(x => (Array.isArray(x) ? x : [x])); console.log(result); // [1, 2, 3, 4]

flatMap() simultaneously transforms elements and flattens one level.


Short version:

MethodWorks withDepthMutatesModern
arr.flat()array1 by defaultNoYes (ES2019+)
arr.flat(Infinity)multidimensionalall levelsNoYes
RecursionarrayanyNoYes (universal)
flatMap()array1 levelNoYes
toString().split()numbers, stringsall levelsNolimited

Conclusion: To "flatten" an array:

javascript
const flat = arr.flat(Infinity);
  • this is short, safe, and clear.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.