Search code examples
javascriptfunctionloopsrootrepeat

Reduce a multi-digit to one-digit -guidance not answer please


goal: take a number like 54321, add the numbers together (5+4+3+2+1 = 15), then take that number (15) add the digits (1+5 = 6), so return 6;

here is my code:

function digital_root(n) {

 if (n >=10) {
  var digits = n.toString().split('').map(function(item, index) {return parseInt(item)}).reduce(function(a,b){ return a+b});
   console.log(digits);
 } 
}

digital_root(1632)

Can't figure out: How to get that function to repeat over and over until digits is just one number (i.e. less than 10). I have tried a variety of nested functions, but can't seem to get it right.

If possible please point me in the direction to the solution ("try a nesting in a while... or read up on..."), but don't give me the complete code solution ("Use this code chunk:...."). I've developed a bad habit of just reading and copying...

Thank you!


Solution

  • You can use recursion to solve this. Write a function makeSingleDigit, which argument will be your number. You need a base condition with the base step, which in your case stops the recursion when received number is one-digit and returns the number. If condition is not true, you just need to get another digit from the number by n%10 and sum it with the makeSingleDigit(Math.floor(n/10)). By this, you repeatedly sum digits of new numbers, until function receives one-digit number.

    Mathematical solution just for your information: the number, which you want to find is n % 9 === 0 ? 9 : n % 9, thus it is the remainder of the division by 9 if it is not 0, otherwise it is 9.