JavaScript: Flatten Nested Array

By Xah Lee. Date: . Last updated: .

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

function xah_flatten_array (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 2017-01-30
    // copyright: free use, must include link and credit

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

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

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

console.log( xah_flatten_array(aa) );

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,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' ]

If all you need is just flatten 1 level, you can use this:

var aa = [1,[9,[3,7]],4];

// flatten array 1 level
console.log(
    Array.prototype.concat.apply([],aa)
); // [ 1, 9, [ 3, 7 ], 4 ]

For a function that flatten n levels, see:

Array Topic

  1. JavaScript: Array Basics
  2. JavaScript: Understand JS Array
  3. JavaScript: Create Array
  4. JavaScript: Sparse Array
  5. JavaScript: Array-Like Object
  6. JavaScript: Array How-To

  1. JavaScript: Array Object
  2. JavaScript: Array.prototype
Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.