Use the Array object
concat() method to merge the multidimensional array into a single-dimensional array:
let fruitsarray = ; fruitsarray = ['apple','orange']; fruitsarray = ['date','strawberry','banana']; fruitsarray = ['tangerine','apricot']; fruitsarray = ['raspberry','kiwi']; // flatten array let newFruitsArray = fruitsarray.concat.apply(,fruitsarray); console.log(newFruitsArray); // 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.concat(fruitsarray,fruitsarray,fruitsarray);
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
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.