Remove leading zeros in a JavaScript array?

To remove leading zeros from a JavaScript array, we use the filter() method with a closure function that tracks when the first non-zero element is encountered. Once a non-zero value is found, all subsequent elements (including zeros) are kept.

Input Examples

[10, 0, 12, 0, 0]
[0, 0, 0, 0, 0, 0, 10, 12, 0]
[12, 0, 0, 1, 0, 0]

Example

const removeLeadingZero = input =>
    input.filter((lastValue => value => lastValue = lastValue || value)
    (false)
);

console.log(removeLeadingZero([10, 0, 12, 0, 0]));
console.log(removeLeadingZero([0, 0, 0, 0, 0, 0, 10, 12, 0]));
console.log(removeLeadingZero([12, 0, 0, 1, 0, 0]));
[ 10, 0, 12, 0, 0 ]
[ 10, 12, 0 ]
[ 12, 0, 0, 1, 0, 0 ]

How It Works

The function uses a closure pattern where:

  • lastValue starts as false and becomes true once a non-zero element is found
  • lastValue || value evaluates to true when either condition is met:
  • We've already found a non-zero element (lastValue is true)
  • The current element is non-zero (value is truthy)
  • Once the first non-zero is encountered, all subsequent elements pass the filter

Alternative Approach

Here's a more readable version using findIndex() and slice():

function removeLeadingZeros(arr) {
    const firstNonZeroIndex = arr.findIndex(value => value !== 0);
    return firstNonZeroIndex === -1 ? [] : arr.slice(firstNonZeroIndex);
}

console.log(removeLeadingZeros([0, 0, 5, 0, 3]));
console.log(removeLeadingZeros([0, 0, 0, 0]));
console.log(removeLeadingZeros([1, 0, 2]));
[ 5, 0, 3 ]
[]
[ 1, 0, 2 ]

Conclusion

Both approaches effectively remove leading zeros while preserving zeros that appear after the first non-zero element. The closure method is more concise, while the findIndex() approach is more readable and handles edge cases explicitly.

Updated on: 2026-03-15T23:18:59+05:30

456 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements