Remove leading zeros in array in 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

The code for this will be −

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

Output

The output in the console will be −

[ 14, 0, 63, 0 ]
raja
Published on 24-Oct-2020 12:04:07
Advertisements