- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Finding place value of a number in JavaScript
We are required to write a function, let’s say 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 number is −
const num = 1234;
Output
Then the output should be −
const output = [1000, 200, 30, 4];
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.
Therefore, 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 −
[ 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 ]
- Related Articles
- Finding number of spaces in a string JavaScript
- Finding persistence of number in JavaScript
- Finding value of a sequence for numbers in JavaScript
- Finding the number of words in a string JavaScript
- Finding closed loops in a number - JavaScript
- Finding product of Number digits in JavaScript
- Finding whether a number is triangular number in JavaScript
- Finding Gapful number in JavaScript
- Finding the largest prime factor of a number in JavaScript
- Finding nearest Gapful number in JavaScript
- Finding the smallest value in a JSON object in JavaScript
- Finding a greatest number in a nested array in JavaScript
- Finding square root of a number without using Math.sqrt() in JavaScript
- Finding nearest prime to a specified number in JavaScript
- Finding a number, when multiplied with input number yields input number in JavaScript

Advertisements