- 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
Return an array populated with the place values of all the digits of a number in JavaScript
We are required to write a function 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 is: const num = 2346; //the output should be: const output = [2000, 300, 40, 6];
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. So, 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 will be −
[ 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
- Sorting digits of all the number of array - JavaScript
- Return an array of all the indices of minimum elements in the array in JavaScript
- Destructively Sum all the digits of a number in JavaScript
- Recursive sum all the digits of a number JavaScript
- Summing all the unique values of an array - JavaScript
- Display all the values of an array in p tag on a web page with JavaScript
- Return indexes of greatest values in an array in JavaScript
- Recursive product of all digits of a number - JavaScript
- Recursively loop through an array and return number of items with JavaScript?
- Return an array with the number of nonoverlapping occurrences of substring in Python
- JavaScript Return an array that contains all the strings appearing in all the subarrays
- Get the number of true/false values in an array using JavaScript?
- Return the first duplicate number from an array in JavaScript
- From an array of arrays, return an array where each item is the sum of all the items in the corresponding subarray in JavaScript
- Convert number to a reversed array of digits in JavaScript

Advertisements