JavaScript: Array.prototype.flat

By Xah Lee. Date: . Last updated: .

New in JS2019.

arrayX.flat()
flatten nested array 1 level. Return a new array.
arrayX.flat(n)
flatten to n times.
const aa = [0, [1, [2, [3, [4]]]]];

console.log(aa.flat());
// [ 0, 1, [ 2, [ 3, [ 4 ] ] ] ]

console.log(aa.flat(1));
// [ 0, 1, [ 2, [ 3, [ 4 ] ] ] ]

console.log(aa.flat(2));
// [ 0, 1, 2, [ 3, [ 4 ] ] ]

console.log(aa.flat(3));
// [ 0, 1, 2, 3, [ 4 ] ]

Array Flatten Patch for pre-JS2019

Here is a function that flatten n levels of nested array.

/* [
xah_flatten_array(array1, n)
flatten nested array n levels. n default to 1
n can be large, such as thousands.

http://xahlee.info/js/js_array_flatten.html
Version 2020-05-12
© 2020-09-07 Xah Lee. free use, must include this section
] */

function xah_flatten_array(array1, n) {
  if (n === undefined) n = 1;
  if (n > 0 && Array.prototype.some.call(array1, Array.isArray)) {
    return xah_flatten_array(Array.prototype.concat.apply([], array1), n - 1);
  } else return array1;
}

// -----------------------------------
// test

// random nested array
const aa = [[26], 0, [1, [2, [3, [4, [5, [6]]]]]], 20];

console.log(xah_flatten_array(aa, 1));

console.log(xah_flatten_array(aa, 2));
console.log(xah_flatten_array(aa, 3));
console.log(xah_flatten_array(aa, 4));
console.log(xah_flatten_array(aa, 5));
console.log(xah_flatten_array(aa, 6));

/* [
[ 26, 0, 1, [ 2, [ 3, [ 4, [Array] ] ] ], 20 ]
[ 26, 0, 1, 2, [ 3, [ 4, [ 5, [Array] ] ] ], 20 ]
[
  26,
  0,
  1,
  2,
  3,
  [ 4, [ 5, [ 6 ] ] ],
  20
]
[
  26,
  0,
  1,
  2,
  3,
  4,
  [ 5, [ 6 ] ],
  20
]
[
  26, 0,     1,
  2,  3,     4,
  5,  [ 6 ], 20
]
[
  26, 0, 1,  2, 3,
   4, 5, 6, 20
]

] */
BUY
ΣJS
JavaScript in Depth