-1

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

5

2 Answers 2

3

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]
    
Sign up to request clarification or add additional context in comments.

Comments

0

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])));

4 Comments

Not sure if this matters, but this approach looks like O(N^2).
it's also mutating the array being iterated, and while forEach closes over the initial array it's still awkward at best
splice is linear time thus making this n2
I answered for the end result, OP didn't mention that that the array would be huge. splice() is probably O(n) since it is linearly deleting at each position. If the input array was like 1000+ degrading performance should be noticeable, but not at a length of 10.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.