JS: Xah Array Flatten (obsolete. 2020)

By Xah Lee. Date: .

JavaScript added function to flatten array.

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 xx = [[26], 0, [1, [2, [3, [4, [5, [6]]]]]], 20];

console.assert(
 JSON.stringify(xah_flatten_array(xx, 1)) ===
  "[26,0,1,[2,[3,[4,[5,[6]]]]],20]",
);

console.assert(
 JSON.stringify(xah_flatten_array(xx, 2)) ===
  "[26,0,1,2,[3,[4,[5,[6]]]],20]",
);

console.assert(
 JSON.stringify(xah_flatten_array(xx, 3)) ===
  "[26,0,1,2,3,[4,[5,[6]]],20]",
);

console.assert(
 JSON.stringify(xah_flatten_array(xx, 4)) ===
  "[26,0,1,2,3,4,[5,[6]],20]",
);

console.assert(
 JSON.stringify(xah_flatten_array(xx, 5)) ===
  "[26,0,1,2,3,4,5,[6],20]",
);

console.assert(
 JSON.stringify(xah_flatten_array(xx, 6)) ===
  "[26,0,1,2,3,4,5,6,20]",
);