Remove leading zeros in a JavaScript array?


To remove leading zeroes in an array, use the concept of filter(). Following is our input wherein we will remove the leading zeroes −

[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]));

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo76.js.

Output

This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo76.js
[ 10, 0, 12, 0, 0 ]
[ 10, 12, 0 ]
[ 12, 0, 0, 1, 0, 0 ]

Updated on: 07-Sep-2020

247 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements