Created
February 8, 2016 09:47
-
-
Save stefanfrede/7a0e81aedd0fa31e1bff to your computer and use it in GitHub Desktop.
These are the three ways to merge a multidimensional array into a single array.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Given: | |
* var myArray = [[1, 2],[3, 4, 5], [6, 7, 8, 9]]; | |
* | |
* Result: | |
* // [1, 2, 3, 4, 5, 6, 7, 8, 9] | |
*/ | |
// Using concat() and apply() | |
var myNewArray1 = [].concat.apply([], myArray); | |
// Using reduce() | |
var myNewArray2 = myArray.reduce(function(prev, curr) { | |
return prev.concat(curr); | |
}); | |
// Using a for loop | |
var myNewArray3 = []; | |
for (var i = 0; i < myArray.length; ++i) { | |
for (var j = 0; j < myArray[i].length; ++j) { | |
myNewArray3.push(myArray[i][j]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment