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

406
Views
Is there any leak in my code, Only 1 case isn't working I don't know why?

I am trying to write a programme to move all the zeroes at the end of the array and retain and the original order of other elements.

Here is my code:-

var moveZeros = function (arr) {

  // TODO: Program me

var k=0;
  for (var i=0;i<=arr.length-1;i++){
    
    var s=arr[i];
    if (s===0){
      
      arr.splice(i,1);
      k++
      
      }
    }
for (var j=0;j<=k-1;j++){


    arr.push(0);


    }

  return arr

  }

But when zeros are next to each other like [1,0,0,1] it doesn't work.

I don't see why.

Can anybody tell?

And please also explain why k-1 not k I wrote k-1 by observing the output. Please don't tell the answer to the original problem I just want to fix the problem with my code. :)

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The problem is that in each loop you increase the i variable by one. Meaning, you go to the next index. But if you have 2 or more zeros in the row, and you remove the first one, you shouldn't change i to i + 1, because i already points at a new value in the array(which is zero) :)

var moveZeros = function (arr) {
  // TODO: Program me

  var k = 0;
  for (var i = 0; i <= arr.length - 1;) {
    var s = arr[i];
    if (s === 0) {
      arr.splice(i, 1);
      k++;
    } else {
      i++;
    }
  }
  for (var j = 0; j <= k - 1; j++) {
    arr.push(0);
  }

  return arr;
};

console.log(moveZeros([1,0,0,2]));

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!