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.

Understanding Place Values

Each digit in a number has a place value based on its position. For example, in 123:

  • 1 is in the hundreds place (1 × 100 = 100)
  • 2 is in the tens place (2 × 10 = 20)
  • 3 is in the units place (3 × 1 = 3)

Using Recursive Approach

We can solve this problem by using a recursive approach that processes digits from right to left:

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));
[ 100, 20, 3 ]

How It Works

The recursive function works as follows:

  1. Extract the last digit using num % 10
  2. Multiply it by the current factor (1, 10, 100, etc.)
  3. Add the result to the beginning of the array using unshift()
  4. Remove the last digit using Math.floor(num / 10)
  5. Increase the factor by 10 and repeat

Alternative Iterative Approach

Here's a non-recursive solution using string manipulation:

const expandNumber = (num) => {
    const str = num.toString();
    const result = [];
    
    for(let i = 0; i  0) {
            result.push(placeValue);
        }
    }
    
    return result;
};

console.log(expandNumber(123));
console.log(expandNumber(1024));
[ 100, 20, 3 ]
[ 1000, 20, 4 ]

Handling Edge Cases

Let's test with numbers containing zeros:

const placeValue = (num, res = [], factor = 1) => {
    if(num){
        const val = (num % 10) * factor;
        if(val > 0) {  // Only add non-zero values
            res.unshift(val);
        }
        return placeValue(Math.floor(num / 10), res, factor * 10);
    };
    return res;
};

console.log(placeValue(1005));
console.log(placeValue(200));
[ 1000, 5 ]
[ 200 ]

Conclusion

Expanding numerals breaks down numbers into their place values. The recursive approach processes digits efficiently, while filtering out zeros gives cleaner results for practical use.

Updated on: 2026-03-15T23:19:00+05:30

170 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements