Skip to content

Instantly share code, notes, and snippets.

@stefanfrede
Created February 8, 2016 09:47
Show Gist options
  • Save stefanfrede/7a0e81aedd0fa31e1bff to your computer and use it in GitHub Desktop.
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.
/**
* 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