How can I split an array of Numbers to individual digits in JavaScript?


We have an array of Number literals, and we are required to write a function, say splitDigit() that takes in this array and returns an array of Numbers where the numbers greater than 10 are splitted into single digits.

For example −

//if the input is:
const arr = [ 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106 ]
//then the output should be:
const output = [ 9, 4, 9, 5, 9, 6, 9, 7, 9, 8, 9, 9, 1, 0, 0, 1, 0, 1, 1,
0, 2, 1, 0, 3, 1, 0, 4, 1, 0, 5, 1, 0, 6 ];

So, let’s write the code for this function, we will use the Array.prototype.reduce() method to split the numbers.

Example

const arr = [ 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106 ]
const splitNum = (n, res = []) => {
   if(n){
      return splitNum(Math.floor(n/10), [n % 10].concat(res));
   };
   return res;
};
const splitDigit = (arr) => {
   return arr.reduce((acc, val) => acc.concat(splitNum(val)), []);
};
console.log(splitDigit(arr));

Output

The output in the console will be −

[
   9, 4, 9, 5, 9, 6, 9, 7, 9,
   8, 9, 9, 1, 0, 0, 1, 0, 1,
   1, 0, 2, 1, 0, 3, 1, 0, 4,
   1, 0, 5, 1, 0, 6
]

Updated on: 25-Aug-2020

414 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements