70 %
Chris Biscardi

Flattening Nested Arrays in JavaScript

I was writing a quick script today and came across a nice use case for .apply to merge nested arrays into a single array. So I figured I’d share it.

javascript
//If we have nested arrays of depth = 1:
var arr = [[1, 2, 3], [4, 5], 6];
//we can flatten it by using concat and apply
var flat_arr = [].concat.apply([], arr);
//and check the value
console.log(flat_arr);
//logs [1,2,3,4,5,6]

If you need a recursive (ie: infinitely nested) array flattened, check out the source for Underscore’s flatten() function, which uses concat.apply for shallow arrays.