- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 ]
Advertisements