Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

146
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda