I want to recursively sum an integer: to split an integer into an array and then sum the individual items until I am left with a single integer array.
This is my logic:
function digital_root(n) {
let digits = (""+n).split("").map(Number);
while (digits.length > 1) {
let result = digits.reduce((sum, int) => sum + int);
let digits = (""+result).split("").map(Number);
}
return digits;
};
This is the error code my Node.js chucks at me (at line 4 in the example code above):
ReferenceError: digits is not defined
at digital_root (repl:6:18)
I'm assuming that the variable digits is accessible inside the scope of the while loop, but obviously, I seem to be wrong? Could someone shed some insight here for me, please?
EDIT: Thank you everyone for your help! I've solved the issue.
For your curiosity, this is the mathematical form underlying my algorithm:
http://mathworld.wolfram.com/DigitalRoot.html
It could also have been solved in one line:
function digital_root(n) {
return (n - 1) % 9 + 1;
}
The inner let for digits (line 5) should be removed
function digital_root(n) {
let digits = (""+n).split("").map(Number);
while (digits.length > 1) {
let result = digits.reduce((sum, int) => sum + int);
digits = (""+result).split("").map(Number);
}
return digits;
}
Issue is let keyword, as let has block level scope, "digits" is not defined at the start of the while loop
Removing let for digits in while loop
function digital_root(n) {
let digits = (""+n).split("").map(Number);
while (digits.length > 1) {
let result = digits.reduce((sum, int) => sum + int);
digits = (""+result).split("").map(Number);
}
return digits;
}
console.log(digital_root(47))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With