Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

188
Visualizações
How to create 2d array using "for" loop in Javascript?

I need to write a program that creates a 2d array in variable "numbers" in rows (5) and columns (4). The elements of the array have to be consecutive integers starting at 1 and end at 20. I have to use "for" loop.

[ 1, 2, 3, 4 ],
[ 5, 6, 7, 8 ],
[ 9, 10, 11, 12 ],
[ 13, 14, 15, 16 ],
[ 17, 18, 19, 20 ],

So I came up with that:

const numbers = [];
const columns = 4;
const rows = 5;

for (let i = 0; i < rows; i++) {
    numbers [i] = [];
    for (let j = 0; j < columns; j++){
        numbers  [i][j] = j + 1;
    }
}
console.log(numbers); 

But the result of this is five identical rows, like this:

      [ 1, 2, 3, 4 ],
      [ 1, 2, 3, 4 ],
      [ 1, 2, 3, 4 ],
      [ 1, 2, 3, 4 ],
      [ 1, 2, 3, 4 ]

Do you have any idea how to fix it? How to make second row starting from 5?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Looks like in the second loop, you should do numbers [i][j] = j * i; instead

about 4 years ago · Juan Pablo Isaza Relatório

0

Every time the outer for loop starts a new iteration, j is reset back to 0, which is why you keep getting rows starting with 1.

To fix this, you could declare a variable outside of the for loops that tracks the current number, and use that instead of j like so:

const numbers = [];
const columns = 4;
const rows = 5;
let currNum = 0;

for (let i = 0; i < rows; i++) {
    numbers [i] = [];
    for (let j = 0; j < columns; j++){
        currNum++;
        numbers  [i][j] = currNum;
    }
}
console.log(numbers); 
about 4 years ago · Juan Pablo Isaza Relatório

0

Here is some updated code. You need to add i*columns to every value

const numbers = [];
const columns = 4;
const rows = 5;

for (let i = 0; i < rows; i++) {
    numbers[i] = [];
    for (let j = 0; j < columns; j++){
        numbers[i][j] = j + 1 + (i*columns);
    }
}
console.log(numbers); 

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda