Search code examples
javascriptarraysloopswhile-looppermutation

HOw to make a loop in all the array untill finish using js


i need to put all items that equals zero att the end of the array, i used a classic permutation code to do that, it works but it does not continu the comparison untill the end.

function moveZeros(arr) {
  var permut = 0;
  var i=0;
 
    while( i <= arr.length) {
      if(arr[i] === 0) {
      permut = arr[i];
      arr[i] = arr[i+1]
       arr[i+1] = "0";
    }
      i++
  }
  return arr.join()
}
console.log(moveZeros([1,2,0,1,0,1,0,3,0,1]))
// i have this : 1,2,1,0,1,0,3,0,1,0
// But Need to have this result : 1, 2, 1, 1, 3, 1, 0, 0, 0, 0


Solution

  • maybe there's another neat way to do it but that's what came into my mind

    1. filter the zeros

    2. know how many zeros were there

    3. add the filtered array to an array with the number of zeros that were there

       let myarr = [1, 2, 0, 1, 0, 1, 0, 3, 0, 1];
       const filtered = myarr.filter(function (ele) {
         return ele !== 0;
       });
       let diff = myarr.length - filtered.length;
       let arrOfZeros = Array(diff).fill(0);
       let reqArr = [...filtered, ...arrOfZeros];
       console.log(reqArr); // (10) [1, 2, 1, 1, 3, 1, 0, 0, 0, 0]