Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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:
-
lastValuestarts asfalseand becomestrueonce a non-zero element is found -
lastValue || valueevaluates totruewhen either condition is met: - We've already found a non-zero element (
lastValueistrue) - The current element is non-zero (
valueis 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.
Advertisements
