Flat Two-Dimensional Array with concat() and apply() in JavaScript

In this tutorials, let’s see how we can flat a two-dimensional array in javascript by using two javascript functions concat() and apply().

Use the Array object concat() method to merge the multidimensional array into a single-dimensional array:

let fruitsarray = [];
fruitsarray[0] = ['apple','orange'];
fruitsarray[1] = ['date','strawberry','banana'];
fruitsarray[2] = ['tangerine','apricot'];
fruitsarray[3] = ['raspberry','kiwi'];

// flatten array
let newFruitsArray = fruitsarray.concat.apply([],fruitsarray);
console.log(newFruitsArray[5]); // tange

The Array object concat() method takes one or more arrays and appends the array elements on to the end of the contents of the parent array on which the method was called. The merged array is then returned as a new array. One use for this type of functionality is to return a single-dimensional array made up of elements from a multidimensional array, as shown in the solution.

I could have flattened the array using the following:

let newFruitsArray = fruitsarray[0].concat(fruitsarray[1],fruitsarray[2],fruitsarray[3]);

But if the array has several members, this approach is tedious and error prone. I could also have used a loop or recursion, but these approaches can be equally tedious. Instead, I used the apply() method. This method allows us to apply the function being called (concat) given an array of arguments. In this case, the array of arguments is the original multidimensional array.

In order for this to work, an empty array is passed as the first parameter to apply(), because concat() works by concatenating the arrays onto an existing array. I can’t use the first element of the array, because its values will be repeated in the final result.

Leave a Reply

Your email address will not be published. Required fields are marked *