1

I'm a newbie to Javascript so please bear with me for this basic question,

I'm trying to get my function to add all the individual digits in a string together, and then keep doing this until I'm left with a single digit!

3253611569939992595156

113 // result of the above digits all added together

5 //result of 1+1+3

I've created a while loop, but it only adds the numbers together once, it dosn't repeat until a single digit and I can't work out why!

function rootFunc(n) {
  var splite = n.toString().split('').map(x => Number(x)); //converts the number to a string, splits it and then converts the values back to a number

  while (splite.length > 1) {
    splite = splite.reduce(getSum);
  }

  return splite;
}

console.log(rootFunc(325361156993999259515));

function getSum(total, num) {
  return total + num;
}

1
  • At a first glance I'm going to say that after you call your reduce fn and modify splite, it becomes a single value, so you won't be looping again. I recommend going over the docs for reduce Commented May 10, 2018 at 16:43

3 Answers 3

2

You're reducing properly, but what you're not doing is re-splitting. Try breaking this out into separate functions:

function digits(n) {
  return n.toString().split('').map(x =>Number(x));
}

Then split each time:

function rootFunc(n) {
  var d = digits(n);
  while (d.length > 1) {
    d = digits(d.reduce(getSum));
  }

  return d;
}
Sign up to request clarification or add additional context in comments.

Comments

1

The problem here is that you return the result after the first splice. You need to have a recursive function. To do this, you can put this before the return :

  if(splite > 9) splite = rootFunc(splite);

This way, you check if the result is greater than 10, if not you do the function with the remaining digits

Comments

1

I was looking this over in jsfiddle, and your number isn't being passed to exact precision, so just console logging n as soon as you call rootFunc, you've already lost data. Otherwise, to fix your loop, you need to remap splite to a string before the end of your codeblock since your while statement is checking .length, which needs to be called on a string. Put this piece of code at the end of the block: splite = splite.toString().split('').map(x =>Number(x));

1 Comment

Hi Bezlonr, thank you for posting your first answer on StackOverflow! To help increase the readability of your answer, please the code snippets into code blocks and object/method/variable names. You can use the editor's code block feature or qwrap the word in backquotes (top left key on PC keyboard). For example this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.