Expanding Numerals in JavaScript


We are required to write a function that, given a number, say, 123, will output an array −

[100,20,3]

Basically, the function is expected to return an array that contains the place value of all the digits present in the number taken as an argument by the function.

We can solve this problem by using a recursive approach.

Therefore, let’s write the code for this function −

Example

The code for this will be −

const num = 123;
const placeValue = (num, res = [], factor = 1) => {
   if(num){
      const val = (num % 10) * factor;
      res.unshift(val);
      return placeValue(Math.floor(num / 10), res, factor * 10);
   };
   return res;
};
console.log(placeValue(num));

Output

The output in the console will be −

[ 100, 20, 3 ]

Updated on: 20-Oct-2020

70 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements