Skip to main content
Stack Overflow
  1. About
  2. For Teams

Return to Revisions

3 of 4
Improved formatting

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]));

Alexey Tseitlin
  • 1.3k
  • 6
  • 19
  • 35
lang-js

AltStyle によって変換されたページ (->オリジナル) /