Design & Download
Your JS Library
in Seconds!!!

Snippet: flatten()

Written by Christopher West (cwest) on December 04, 2015.
Turns an array with sub-arrays into an array without sub-arrays. Provides to option to do this recursively until even the sub-arrays of sub-arrays and all subsequent sub-arrays are merged into one array in the order found.
function flatten(arr, opt_deep) {
  arr = slice(arr);
  for (var e, i = arr.length; i--;) {
    if (typeOf(e = arr[i], 'Array')) {
      arr.splice.apply(arr, [i, 1].concat(opt_deep ? flatten(e, 1) : e));
    }
  }
  return arr;
}

flatten(...) API Documentation

Turns an array with sub-arrays into an array without sub-arrays. Provides the option to do this recursively until even the sub-arrays of sub-arrays and all subsequent sub-arrays are merged in to make one large array.

Parameters

  1. arr {Array}:
    The array that will be duplicated and whose sub-arrays will be merged into the duplicated array in the place in which they are found.
  2. opt_deep {boolean=}:
    Optional. Defaults to false. If true even sub-arrays of sub-arrays will be merged into the returned duplicate of arr in the place they are found so that no sub-arrays will be present in the returned array. If false only sub-arrays of arr will be merged into the returned duplicate of arr, leaving any sub-arrays of sub-arrays in as is without recursively mergining them into the returned array.

Returns

Returns a duplicate of arr where the sub-arrays are merged in place and if opt_deep is true even the sub-arrays of sub-arrays and beyond will be merged in making it so no sub-arrays exist.