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

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

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 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