Trying to do the digitalroot code wars challenge, where you add the digits of a number together until it is down to a single digit number.
My code returns an “undefined” even though the console.log(n) commands shows the correct value for the variable. Any pointers would be appreciated. Thanks much!
// add the digits of the numbers together, return the final sum
function digital_root(n) {
console.log(n);
if (n <= 9)
return n;
else{
// use recursion!
var numString = n.toString();
var stringArr = numString.split('');
var toNums = stringArr.map((e)=> parseInt(e));
var sumNums = toNums.reduce((acc, curr) => acc + curr );
digital_root(sumNums);
}
}
console.log(digital_root(16));
// add the digits of the numbers together, return the final sum
function digital_root(n) {
console.log(n);
if (n <= 9)
return n;
else{
// use recursion!
var numString = n.toString();
var stringArr = numString.split('');
var toNums = stringArr.map((e)=> parseInt(e));
var sumNums = toNums.reduce((acc, curr) => acc + curr );
// digital_root(sumNums);
return sumNums;
}
}
Oh my gosh, just missing a “return” word. Frustrating. Now I just have to peel the keys out of my forehead. Thanks so much, Owel. And than you too, Dawson, for responding. Tight, concise answer.