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

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.

Problem

Given an array containing zeros and non-zero elements, we need to move all zeros to the end while maintaining the relative order of non-zero elements.

Method 1: Using Two-Pass Approach

This approach first collects non-zero elements, then adds zeros at the end:

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, 0, el);
            currIndex++;
        }
    }
    return res;
};

console.log(moveAllZero(arr));
[
  5, 1, -3, 4,
  6, 0, 0, 0
]

Method 2: Simpler Two-Array Approach

A cleaner approach that separates non-zero elements and zeros:

const moveZeroesToEnd = (arr) => {
    const nonZeros = [];
    const zeros = [];
    
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] === 0) {
            zeros.push(0);
        } else {
            nonZeros.push(arr[i]);
        }
    }
    
    return nonZeros.concat(zeros);
};

const testArray = [0, 1, 0, 3, 12];
console.log(moveZeroesToEnd(testArray));
[ 1, 3, 12, 0, 0 ]

Method 3: In-Place Solution

For memory efficiency, we can modify the original array in-place:

const moveZerosInPlace = (arr) => {
    let writeIndex = 0;
    
    // Move all non-zero elements to the front
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] !== 0) {
            arr[writeIndex] = arr[i];
            writeIndex++;
        }
    }
    
    // Fill remaining positions with zeros
    while (writeIndex < arr.length) {
        arr[writeIndex] = 0;
        writeIndex++;
    }
    
    return arr;
};

const nums = [0, 1, 0, 3, 12, 0, 8];
console.log(moveZerosInPlace(nums));
[ 1, 3, 12, 8, 0, 0, 0 ]

Comparison

Method Time Complexity Space Complexity Modifies Original
Two-Pass with Splice O(n²) O(n) No
Two-Array Approach O(n) O(n) No
In-Place Solution O(n) O(1) Yes

Conclusion

The in-place solution is most efficient with O(n) time and O(1) space complexity. Use the two-array approach when you need to preserve the original array and want optimal time complexity.

Updated on: 2026-03-15T23:19:00+05:30

607 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements