Flatten An Array Of Arrays

There can be times when working with arrays that you need to be able to turn the array into one dimension. For example, you may have a situation whereby you have the following array:

[ [ 1, 2 ], [ 3, 4, 5 ], [ 6 ], [ 7, 8 ], [ 9 ] ]

And you just want to be able to transform that array such that it is magically turned into something like this:

[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

So how do we do this in Javascript?

Well, thankfully there’s an easy way! And the reduce function can help to flatten 2d arrays.

Here’s what the reduce function looks like with it’s arguments and parameters:

Array.prototype.reduce( function( previousValue, element, index, array ) { 
    //...
}, initialValue ); 

So, given the following array:

var arr = [ [ "a", "b" ], [ "c" ], [ "d", "e" ] ];

var flat = arr.reduce( function( a, b ) {
    return a.concat( b );
});

console.log( flat ); // => [ "a", "b", "c", "d", "e" ]

What this reduce function does is take a previousValue parameter as the first parameter then a currentValue as the second parameter and whatever is returned from this function is what is inserted into the previousValue parameter.

Therefore if we were looking at this example at each iteration it would look as follows:

passpreviousValueelementindexarrayreturn
first pass0[ “a”, “b” ]0arr[ “a”, “b” ]
second pass[ “a”, “b” ][ “c” ]1arr[ “a”, “b”, “c” ]
third pass[ “a”, “b”, “c” ][ “d”, “e” ]2arr[“a”, “b”, “c”, “d”, “e” ]

However, in the following example note what happens when the first element in the 2-dimensional array is NOT an array:

var arr = [ "a", [ "c" ], [ "d", "e" ] ];

var flat = arr.reduce( function( a, b ) {
    return a.concat( b );
});

console.log( flat ); // =>"acd,e"

Here, we need to be mindful that because the FIRST item in this array is NOT an array itself it will cause the remainder of the elements within the array to be concatenated as a sting.

Therefore, to get around this we should take advantage of the optional initialValue parameter after the callback function and we would therefore modify our code as follows:

var arr = [ "a", [ "c" ], [ "d", "e" ] ];

var flat = arr.reduce( function( a, b ) {
    return a.concat( b );
}, [] ); // <= note what happens here!

console.log( flat ); // => [ "a", "c", "d", "e" ]

We could have similarly used the same initialValue in our first example and this would have given us the same result.

This certainly comes in handy when working with Google Spreadsheets!