Finding place value of a number in JavaScript


We are required to write a function, let’s say splitNumber() that takes in a positive integer and returns an array populated with the place values of all the digits of the number.

For example −

If the input number is −

const num = 1234;

Output

Then the output should be −

const output = [1000, 200, 30, 4];

Let’s write the code for this function.

This problem is very suitable for a recursive approach as we will be iterating over each digit of the number.

Therefore, the recursive function that returns an array of respective place values of digits will be given by −

Example

const splitNumber = (num, arr = [], m = 1) => {
   if(num){
      return splitNumber(Math.floor(num / 10), [m * (num % 10)].concat(arr), m * 10);
   }
   return arr;
};
console.log(splitNumber(2346));
console.log(splitNumber(5664));
console.log(splitNumber(3453));
console.log(splitNumber(2));
console.log(splitNumber(657576));
console.log(splitNumber(345232));

Output

The output in the console −

[ 2000, 300, 40, 6 ]
[ 5000, 600, 60, 4 ]
[ 3000, 400, 50, 3 ]
[ 2 ]
[ 600000, 50000, 7000, 500, 70, 6 ]
[ 300000, 40000, 5000, 200, 30, 2 ]

Updated on: 17-Oct-2020

549 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements