JavaScript | Flattening Arrays


If you have nested arrays one level deep and they need flattening, try this out…

// A nested array one-level deep
var array = [[ a, b ], [ c, d, e ], f, g];

// Using the built-in concat and apply functions
var flattened = [].concat.apply([],array);

// Output
console.log(flattened);
// [a, b, c, d, e, f]

Note: for infinitely nested Underscore.js has a flatten function

flatten_.flatten(array, [shallow]) Flattens a nested array (the nesting can be to any depth). If you pass shallow, the array will only be flattened a single level.

_.flatten([1, [2], [3, [[4]]]]);
=> [1, 2, 3, 4];

_.flatten([1, [2], [3, [[4]]]], true);
=> [1, 2, 3, [[4]]];