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

149
Visualizações
using splice inside 2D Array in Javascript

I've created this 2D array, and I'm trying to delete the rows that are having 5 "ones" or more, I tried it with splice (a.splice(j,1)) but it doesn't work . I think because when using this method it changes the whole quantity of rows and that's affects the for loops.

Is it because I don't use splice correctly or should I use different method ?

Thanks !

a = Array(7).fill(0).map(x => Array(10).fill(0))

for (let i = 0; i < 5; i++) {
  a[1][i + 2] = 1;
  a[4][i + 2] = 1;
  a[5][i + 2] = 1;
}

console.log(a);


let count = 0;
for (let j = 0; j < 7; j++) {
  for (let i = 0; i < 10; i++) {
    if (a[j][i] == 1) {
      count = count + 1;
    }
  }
  if (count > 4) {
    console.log("Line" + j);
    // a.splice(j,1);
  }
  count = 0;
  // a.splice(j,1);
}

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

0

Your splice is correct but you move forward through the array (j is incremented). To do this type of operation you need to move backward through the array (j is decremented) - this way the changing array indices don't intefere with your loop.

See the example below:

a = Array(7).fill(0).map(x => Array(10).fill(0))

for (let i=0; i<5; i++) {
  a[1][i+2] = 1;
  a[4][i+2] = 1;
  a[5][i+2] = 1;
}

console.log("Original array");
console.log(a);

for (let j = a.length - 1; j > 0; j--) {
  var count;
  
  for (let i = 0; i < a[j].length; i++) {
    if (a[j][i] === 1) {
      count += 1
    }
  }
  
  if (count > 4) {
    a.splice(j, 1);
  }
  
  count = 0;
}

console.log("Filtered array");
console.log(a);

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