RajuPedda
RajuPedda

Reputation: 3379

How to remove leading zeros from the Array of Numbers in Javascript

 let array = [000232, 0043, 0000454523, 0234]

Expected output: [232, 43, 454523, 234]

There are lots of ways, where we can remove leading zeros if it is a string or arrays of strings.

arr.map( (value) => { console.log(parseInt(value, 10) )})

So, what I tried, to convert those Array of numbers to string values:

1. array.map(String);
2. array.join().split(',');

But it's not working as expected.

Any help would be appreciated.

Upvotes: 1

Views: 1006

Answers (2)

Saurabh Agrawal
Saurabh Agrawal

Reputation: 7739

Try this:

  let tmpArray = [000232, 0043, 0000454523, 0234];
  let row1 = tmpArray.map(function (val) {
    return Number(val.toString(8));
  });
  console.log(row1);

Upvotes: 2

Nina Scholz
Nina Scholz

Reputation: 386634

With leding zero, you use octal numbers. To get decimals, you need to convert back to octals and parse this values as decimal numbers.

This approach works only on an array of octal numbers. It is not possible, to check if a value is taken from an octal literal.

let array = [000232, 0043, 0000454523, 0234],
    values = array.map(n => parseInt(n.toString(8), 10));

console.log(values);

Upvotes: 7

Related Questions