Return an array populated with the place values of all the digits of a number in JavaScript



We are required to write a function 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 is:
const num = 2346;
//the output should be:
const output = [2000, 300, 40, 6];

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. So, 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 will be −

[ 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 ]
raja
Published on 25-Aug-2020 07:46:13
Advertisements