Alexey Tseitlin Alexey Tseitlin - 2 months ago 5
Javascript Question

Create 2D array from 1D array using loop (JavaScript)

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

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