I have an array: [1, 2, 3, 4, 5, 6, 7, 8, 9]
I want to create a 2D array with three 1D arrays. Each NUM in the function variables is the length of each 1D array.
The result should be [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
But all I get is ,,3,,,6,,,9. What am I doing wrong?
function infiniteLoop(arr, num) {
var answer = [];
var count = 0;
for (let i = 0; i < num.length; i++) {
for (let j = 0; j < num[i]; j++, count++) {
answer[i] = [];
answer[i][j] = arr[count];
}
}
return answer;
}
document.write(infiniteLoop([1, 2, 3, 4, 5, 6, 7, 8, 9], [3, 3, 3]));
answer[i] = [];part in the wrong place. Have another look at my answer, or Thomas's (but don't usenew Array()).