Flatten Array Containing Arrays in JavaScript

javascript
Published on December 20, 2019

Use-Cases of this tutorial

  • Know how to convert an array containing arrays as elements, to a single 1-dimensional array.
  • Know about Array.flat() method.

An array can be flattened in Javascript using the flat() method.

Flattening an array refers to the process taking an input array, which may itself contain n-dimensional arrays as its elements, to a single array.

// input array containing 1-dimensional arrays
[1, 2, 3, [4, 5], [6, 7]];

// flattened array
[1, 2, 3, 4, 5, 6, 7];
// input array containing 2-dimensional array
[1, 2, 3, [[4, 5], [6, 7]]];

// flattened array up to level 1
[1, 2, 3, [4, 5], [6, 7]];

// flattened array up to level 2
[1, 2, 3, 4, 5, 6, 7];
// input array containing mix of n-dimensional arrays
[1, 2, 3, [4, 5], [[6, 7], 8], [9, 10, [11, 12, [13, 14]]]];

// flattened array up to maximum level
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14];

Doing this was not very direct in JavaScript, but with ES 2019 a method has been provided that flattens an array to the required level.

Array.flat()

The flat() method flattens the calling array up to a specified level / depth of the nested arrays.

The depth can be provided through a numeric parameter to flat(). The default value is 1. If the level of nesting is not known, or flattening is to be done till the maximum, Infinity keyword can be passed.

flat() returns the flattened array. Original array is not changed.

Some examples are given below to demonstrate working of flat() method.

var arr = [1, 2, 3, [4, 5]];

// [1, 2, 3, 4, 5]
console.log(arr.flat());
var arr = [1, 2, 3, [[4, 5], [6, 7]]];

// [1, 2, 3, [4, 5], [6, 7]]
console.log(arr.flat());

// [1, 2, 3, 4, 5, 6, 7]
console.log(arr.flat(2));

// [1, 2, 3, 4, 5, 6, 7]
console.log(arr.flat(Infinity));
var arr = [1, 2, 3, [4, 5], [[6, 7], 8], [9, 10, [11, 12, [13, 14]]]];

// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14];
console.log(arr.flat(Infinity));
In this Tutorial