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.

//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.

Join the Newsletter

My newsletter is where you'll find exclusive content from me. I write about technology, startups, and why you shouldn't call yourself a junior engineer

Web Mentions