Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

148
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!