JS: Array.prototype.flat (Flatten Array)
New in JS2019.
arrayX.flat()
- flatten nested array 1 level. Return a new array.
arrayX.flat(n)
-
flatten n times.
const xx = [0, [1, [2, [3, [4]]]]]; console.log(JSON.stringify(xx.flat()) === "[0,1,[2,[3,[4]]]]"); console.log(JSON.stringify(xx.flat(1)) === "[0,1,[2,[3,[4]]]]"); console.log(JSON.stringify(xx.flat(2)) === "[0,1,2,[3,[4]]]"); console.log(JSON.stringify(xx.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 xx = [[26], 0, [1, [2, [3, [4, [5, [6]]]]]], 20]; console.log( JSON.stringify(xah_flatten_array(xx, 1)) === "[26,0,1,[2,[3,[4,[5,[6]]]]],20]", ); console.log( JSON.stringify(xah_flatten_array(xx, 2)) === "[26,0,1,2,[3,[4,[5,[6]]]],20]", ); console.log( JSON.stringify(xah_flatten_array(xx, 3)) === "[26,0,1,2,3,[4,[5,[6]]],20]", ); console.log( JSON.stringify(xah_flatten_array(xx, 4)) === "[26,0,1,2,3,4,[5,[6]],20]", ); console.log( JSON.stringify(xah_flatten_array(xx, 5)) === "[26,0,1,2,3,4,5,[6],20]", ); console.log( JSON.stringify(xah_flatten_array(xx, 6)) === "[26,0,1,2,3,4,5,6,20]", );