JavaScript: Flatten Nested Array

By Xah Lee. Date: .

Here's a function that flatten n levels of nested array.

function flattenArray (arrayX, n) {
    // flatten nested array n levels. n default to 1
    // n can be large, such as thousands. because when array no longer has element that's array, the function return it immediately
    // http://xahlee.info/js/js_array_flatten.html
    // version 2016-04-25
    // copyright: free use, must include link and credit

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

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

var aa = [0,[1,[2,[3,[4,[5,[6]]]]]],"some"];

console.log(
    flattenArray(aa)
);

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

console.log(
    flattenArray(aa,2)
);

console.log(
    flattenArray(aa,3)
);

console.log(
    flattenArray(aa,4)
);

console.log(
    flattenArray(aa,400)
);

// prints

// [ 0, 1, [ 2, [ 3, [Object] ] ], 'some' ]
// [ 0, 1, [ 2, [ 3, [Object] ] ], 'some' ]
// [ 0, 1, 2, [ 3, [ 4, [Object] ] ], 'some' ]
// [ 0, 1, 2, 3, [ 4, [ 5, [Object] ] ], 'some' ]
// [ 0, 1, 2, 3, 4, [ 5, [ 6 ] ], 'some' ]
// [ 0, 1, 2, 3, 4, 5, 6, 'some' ]

back to JavaScript: Array How-To

Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.