Remove leading zeros in array - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

The requirements for this question are simple. We are required to write a JavaScript function that takes in an array of Numbers. If the array contains leading zero, the function should remove the leading zeros in place, otherwise the function should do nothing.

For example −

If the input array is −

const arr = [0, 0, 0, 14, 0, 63, 0];

Then the output should be −

const output = [14, 0, 63, 0];

Therefore, let's write the code for this function

Example

Following is the code −

const arr = [0, 0, 0, 14, 0, 63, 0];
const removeLeadingZero = arr => {
   while (arr.indexOf(0) === 0) {
      arr.shift();
   };
};
removeLeadingZero(arr);
console.log(arr);

This will produce the following output on console −

[ 14, 0, 63, 0 ]
raja
Published on 01-Oct-2020 10:50:15
Advertisements