Flattening a Two-Dimensional Array with concat()
and apply()
Problem
You want to flatten a two-dimensional array.
Solution
Use the Array object concat() method to merge the multidimensional array into a
single-dimensional array:
var fruitarray = []; fruitarray[0] = ['strawberry','orange']; fruitarray[1] = ['lime','peach','banana']; fruitarray[2] = ['tangerine','apricot']; fruitarray[3] = ['raspberry','kiwi']; // flatten array var newArray = fruitarray.concat.apply([],fruitarray); console.log(newArray[5]); // tangerine
EXPLAIN
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 func‐ tionality is to return a single-dimensional array made up of elements from a multidi‐ mensional array, as shown in the solution.
I could have flattened the array using the following:
var newArray = fruitarray[0].concat(fruitarray[1],fruitarray[2],fruitarray[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.
No comments:
Post a Comment