Javascript Program to Move all zeroes to end of array | Set-2 (Using single traversal)
Last Updated :
23 Jul, 2025
Given an array of n numbers. The problem is to move all the 0's to the end of the array while maintaining the order of the other elements. Only single traversal of the array is required.
Examples:
Input : arr[] = {1, 2, 0, 0, 0, 3, 6}
Output : 1 2 3 6 0 0 0
Input: arr[] = {0, 1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9}
Output: 1 9 8 4 2 7 6 9 0 0 0 0 0Algorithm:
moveZerosToEnd(arr, n)
Initialize count = 0
for i = 0 to n-1
if (arr[i] != 0) then
swap(arr[count++], arr[i])
JavaScript
// JavaScript implementation to move all zeroes at
// the end of array
// function to move all zeroes at
// the end of array
function moveZerosToEnd(arr, n) {
// Count of non-zero elements
let count = 0;
// Traverse the array. If arr[i] is non-zero, then
// swap the element at index 'count' with the
// element at index 'i'
for (let i = 0; i < n; i++)
if (arr[i] != 0) {
temp = arr[count];
arr[count] = arr[i];
arr[i] = temp;
count = count + 1;
}
}
// function to print the array elements
function printArray(arr, n) {
let output = ""
for (let i = 0; i < n; i++)
output += arr[i] + " ";
console.log(output);
}
// Driver program to test above
let arr = [0, 1, 9, 8, 4, 0, 0, 2,
7, 0, 6, 0, 9];
let n = arr.length;
console.log("Original array: ");
printArray(arr, n);
moveZerosToEnd(arr, n);
console.log("Modified array: ");
printArray(arr, n);
Output:
Original array: 0 1 9 8 4 0 0 2 7 0 6 0 9
Modified array: 1 9 8 4 2 7 6 9 0 0 0 0 0
Complexity Analysis:
- Time Complexity: O(n).
- Auxiliary Space: O(1).
Please refer complete article on Move all zeroes to end of array | Set-2 (Using single traversal) for more details!
Explore
JavaScript Basics
Array & String
Function & Object
OOP
Asynchronous JavaScript
Exception Handling
DOM
Advanced Topics