- Trending Categories
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
Convert number to tens, hundreds, thousands and so on - 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.
Example
Following is the code −
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
This will produce the following output in console −
[ 100, 20, 3 ]
Advertisements