Warning: Under Construction. I am using this site as my playground as I build gatsby-mdx and gatsby themes. During this time I will also repost new content to Medium

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