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]));
4 Answers 4
JavaScript doesn't have multidimensional arrays per se, what it has is arrays of arrays.
When you try to use answer[i][j] the answer[i] part of that is undefined because you haven't set it to anything yet - at that point answer is just an empty array. You need to set answer[i] = []; to set the first element of answer to be an empty array, and then you can use answer[i][j].
That will fit in your existing loop like this:
for (let i = 0; i < num.length; i++) {
answer[i] = []; // <--- add this
for (let j = 0; j < num[i]; j++, count++) {
answer[i][j] = arr[count];
}
}
Comments
Without testing it I believe you need to set answer[i] = [] before you loop your next array
Comments
answer[i] hasn't been created. You are trying to assign a value to something that doesn't exist. You need to create answer[i] like this:
answer[i] = new Array(num[i]);
So, the full code:
function infiniteLoop(arr, num) {
var answer = [];
var count = 0;
for (var i = 0; i < num.length; i++) {
answer[i] = new Array(num[i]);
for (var j = 0; j < num[i]; j++, count++) {
answer[i][j] = arr[count];
}
}
return answer;
}
document.write(infiniteLoop([1, 2, 3, 4, 5, 6, 7, 8, 9], [3, 3, 3]));
Comments
The problem is that answer[i] is undefined. The solution would be to add the following statement to the beginning of the first for loop:
answer[i] = [];
This should initialize answer[i] as an array, thus allowing you to set individual indices for it.
answer[i] = [];part in the wrong place. Have another look at my answer, or Thomas's (but don't usenew Array()).