Sum up a number until it becomes 1 digit JS
If you're looking for short, it's hard to beat:
var n = 5678;
sum = n % 9 || 9;
console.log(sum)
If you're curious about how that works, see: casting out nines.
You can do this using recursion, here is an example:
function getOneDigit(nr){
let asStr = nr.toString();
let sum = asStr.split("").reduce((a, c) => {
a+=parseInt(c);
return a;
}, 0);
return sum >= 10 ? getOneDigit(sum) : sum;
}
[234235, 235346, 657234, 1, 2, 5423].forEach(nr => console.log(getOneDigit(nr)));
This line of code does this.
function digital_root(n) {
return (n - 1) % 9 + 1;
}
When you take the modulo of a number with 9, it becomes a 1 less than 9. So, when you have 10%9, you will get 1, which is equal to 1+0.
Similarly, 123%9 = 6.
Why (n-1)%9 and added 1: Because when you input 9, it became 0 so input will be invalid.
For n=9, this method will return (9-1)%9 = 8 and 8+1 = 9.
So it does not break.
You can also write
return n%9 || 9