Moving all zeroes present in the array to the end in JavaScript


Problem

We are required to write a JavaScript function that takes in an array of literals that might contain some 0s. Our function should tweak the array such that all the zeroes are pushed to the end and all non-zero elements hold their relative positions.

Example

Following is the code −

 Live Demo

const arr = [5, 0, 1, 0, -3, 0, 4, 6];
const moveAllZero = (arr = []) => {
   const res = [];
   let currIndex = 0;
   for(let i = 0; i < arr.length; i++){
      const el = arr[i];
      if(el === 0){
         res.push(0);
      }else{
         res.splice(currIndex, undefined, el);
         currIndex++;
      };
   };
   return res;
};
console.log(moveAllZero(arr));

Output

Following is the console output −

[
   5, 1, -3, 4,
   6, 0, 0, 0
]

Updated on: 17-Apr-2021

417 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements