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

177
Visualizações
Insert 1 value in 2d array in javascript

I need some help with my code. I try to insert only one value in each array. I need to fill in the row first and after that, if the row is full then move to the next column. I try to solve this part for a couple of days but I fail. So here is my code

const testData = [1,2,3,4,5,6,7,8,9];                
const create2dArray = (row, column) => {
                    var result = [];
                    for(let i = 0; i< row; i++){
                        result[i]= [];
                        for(let j = 0; j<column; j++){   
                            result[i][j] = [];
                            for(let e = 0; e < testData.length; e++){
                            result[i][j] = [testData[e]];
                            }
                        }
                    }
                    return result;
            
                }
            let Column = 5
            let Row = 5
            filterQuotaData(EnrollmentQuota);
            var ground = create2dArray(Column,Row);
            console.log(ground);

Suppose the output is :

[1],[2],[3],[4],[5]
[6],[7],[8],[9],[]
[],[],[],[],[]
[],[],[],[],[]
[],[],[],[],[]

instead, I got:

[9],[9],[9],[9],[9]
[9],[9],[9],[9],[9]
[9],[9],[9],[9],[9]
[9],[9],[9],[9],[9]
[9],[9],[9],[9],[9]

I hope someone can help me to solve this problem

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

0

Following code

const testData = [1,2,3,4,5,6,7,8,9];                
const create2dArray = (row, column) => {
                    var result = [];
                    k = 0
                    for(let i = 0; i< row; i++){
                        result[i]= [];
                        for(let j = 0; j<column; j++){   
                            if(k < testData.length) {
                              result[i][j] = [testData[k]];
                            } else {
                              result[i][j] = [];
                            }
                            k++
                        }
                    }
                    return result;
            
                }
            let Column = 5
            let Row = 5
            //filterQuotaData(EnrollmentQuota);
            var ground = create2dArray(Column,Row);
            console.log(ground);

produces

[
  [ [ 1 ], [ 2 ], [ 3 ], [ 4 ], [ 5 ] ],
  [ [ 6 ], [ 7 ], [ 8 ], [ 9 ], [] ],
  [ [], [], [], [], [] ],
  [ [], [], [], [], [] ],
  [ [], [], [], [], [] ]
]

Does it what you need?

about 4 years ago · Juan Pablo Isaza Relatório

0

What's happening in your code is that you have the 3rd loop adding everything to each column from 2nd loop. The reason why they are all 9s is because you are overwriting each column by using an assignment instead of adding it to the array:

// 3rd loop
array[0][0][0] = 1 // 1st iteration [[[1],...]]
array[0][0][1] = 2 // 2nd iteration [[[2],...]]

Here's an example that uses 2 loops and pushes sub-arrays and shifts from test array.

const test = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const create2dArray = (row, column) => {
  let result = [];
  for (let r = 0; r < row; r++) {
    result.push([]);
    for (let c = 0; c < column; c++) {
      let data = test.length < 1 ? [] : [test.shift()]
      result[r].push(data);
    }
  }
  return result;
}
let row = 5, col = 5;

let ground = create2dArray(row, col);
console.log(JSON.stringify(ground));

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