Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass a variable into a JS while loop?

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:

  1. Take an integer (n) and split it into an array.
  2. Sum all the individual numbers.
  3. Is the number greater than 9?
    1. YES: Repeat steps 1 and 2
    2. NO: Return the number
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;
}
like image 649
Richard Jarram Avatar asked Nov 21 '25 11:11

Richard Jarram


2 Answers

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;
}
like image 140
izem Avatar answered Nov 22 '25 23:11

izem


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))
like image 31
Naga Sai A Avatar answered Nov 23 '25 01:11

Naga Sai A