Home > Software design >  HOw to make a loop in all the array untill finish using js
HOw to make a loop in all the array untill finish using js

Time:01-05

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

CodePudding user response:

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]
    

CodePudding user response:

Simply remove each with .splice() 0 and push() a 0 to the end of the array. Note, .forEach(), .splice(), and .push() are array methods that mutate the array original array.

function moveZeros(array) {
  array.forEach((number, index) => {
    if (number === 0) {
      array.splice(index, 1);
      array.push(0);
    }
  });
  return array;
}
console.log(JSON.stringify(moveZeros([1,2,0,1,0,1,0,3,0,1])));

  • Related