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(depth)
flatten to depth level.
const aa = [0,[[2,[3]],1]];

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

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

Polyfill

Here's 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

/* [
xah_is_array_equal(array1, array2)
Return true if 2 array are equal
Allow array-like object
Allow nested array

http://xahlee.info/js/js_comparison_equality_test_objects.html
version 2019-04-24
 ] */
const xah_is_array_equal = ((array1, array2) =>
{
    // allow array-like object
    if ( Array.isArray(array1) !== Array.isArray(array2) ) { return false; }
    if (array1.length !== array2.length) { return false; }

    return Array.prototype.every.call(
        array1,
        ((x, i) => {
            const y = array2[i];
            if ( Array.isArray(x) ) {
                if ( ! Array.isArray(y) ) {
                    return false;}
                else {
                    return xah_is_array_equal(x, y); }
            } else if ( typeof x === "object" && typeof x !== null) {
                if (! ( typeof y === "object" && typeof y !== null)) {
                    return false;}
                else {
                    return xah_is_obj_equal(x,y); }
            } else {
                return (x === y);
            }
        })
    );
});

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

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

console.log( [1,2,3,4,5,6,7,8]. every ( (x => xah_is_array_equal( aa.flat(x), xah_flatten_array(aa,x) )) ) );
// true
JS in Depth
XAH  BUY NOW

JS in Depth

JS Obj Ref

DOM


JS Obj Ref

Array

prototype