I don't understand why it not work correct ? Help!

console.clear();
function digital_root(n) {
    let arrArgument = n.toString();
    let newArray = arrArgument.split('');
    console.log(newArray);
  let acum = 0;
  for(let i = 0;i < newArray.length;i++){
   // console.log(newArray[i]);
    acum +=Number(newArray[i]);
    if(acum.toString().length >= 2){
     // console.log(acum.toString().length);
      digital_root(acum);
    }
    else{
      
    }
  }
  console.log(acum);
      return acum;
}
digital_root(1126);

I’ll show you the approach that I would use and then your code modified.

Notice I renamed some of your variables to meaningful names.

  const digitalRoot = (number) => {

        // splits numbers individually and adds them together
        let sum = number.toString()
                        .split('')
                        .reduce((a, b) => Number(a) + Number(b), 0);

        // gets length of numbers
        const sumLength = sum.toString().length;

        // continue repeating process until the length of numbers is 1.
        if (sumLength >= 2){
            sum = digitalRoot(sum);
        }

        return sum;
    };

const dr = digitalRoot(65536);
console.log(dr);


    function digital_root2(number) {
        let numberStr = number.toString();
        let sum = 0;
        for (let i = 0; i < numberStr.length; i++){
            sum += Number(numberStr[i]);
            if(sum.toString().length >= 2){
                sum = digital_root2(sum);
            }
        }
        
        return sum;
    }


const dr2 = digital_root2(65536);
console.log(dr2);

Notice how I removed your .split() since you don’t need to make it into an array.

You can and you should in lot of cases. Read up on recursion. :slight_smile:

1 Like
function foo(){ 
    console.log('ready')
    foo()
}
foo()

computer couldnt handle it lol

You only use recursion in cases where your foo() function have a case in which it will stop execution and return value.
For example:

function foo(number){
if (number>0) return foo(number-1)+number;
return 0;
}

console.log( foo(3) )

foo(10) // what is sum of all elements until 10?
This is simple example so should be easy to understand how it works. Because each new call to foo reduces input, and because it stops operation once input is past some point, this function will work and is working example of recursion.

you original code works fine btw

heres a neat version because why not

const digital_root = num =>
  num
    .toString()
    .split("")
    .map(i => parseInt(i))
    .reduce((a, b) => a + b);

thats sick. ill have to remember to use that in something