Created
March 24, 2014 09:23
-
-
Save amboy00/9737014 to your computer and use it in GitHub Desktop.
Simple function to turn simple arrays to multidimensional. Found here: http://stackoverflow.com/questions/4492385/how-to-convert-simple-array-into-two-dimensional-arraymatrix-in-javascript-or
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
function listToMatrix(list, elementsPerSubArray) { | |
var matrix = [], i, k; | |
for (i = 0, k = -1; i < list.length; i++) { | |
if (i % elementsPerSubArray === 0) { | |
k++; | |
matrix[k] = []; | |
} | |
matrix[k].push(list[i]); | |
} | |
return matrix; | |
} | |
var matrix = listToMatrix([1, 2, 3, 4, 4, 5, 6, 7, 8, 9], 3); | |
// result: [[1, 2, 3], [4, 5, 6], [7, 8, 9]] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment