Write an algorithm that takes an array and moves all of the zeros to the end JavaScript


We have to write a function that takes in an array and moves all the zeroes present in that array to the end of the array without using any extra space. We will use the Array.prototype.forEach() method here along with Array.prototype.splice() and Array.prototype.push().

The code for the function will be −

Example

const arr = [34, 6, 76, 0, 0, 343, 90, 0, 32, 0, 34, 21, 54];
const moveZero = (arr) => {
   for(ind = 0; ind < arr.length; ind++){
      const el = arr[ind];
      if(el === 0){
         arr.push(arr.splice(ind, 1)[0]);
         ind--;
      };
   }
};
moveZero(arr);
console.log(arr);

Output

The output in the console will be −

[34, 6, 76, 343, 90, 32, 34, 21, 54, 0, 0, 0, 0]

Updated on: 24-Aug-2020

243 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements