Add the digits up

this is a helper function, along with three other’s it should be called as a .filter(); to return only prime numbers. It is for one of the exercises at FreeCodeCamp.com, Sum all Primes.

I’m just trying to accumulate the charAt(*) for each n,
so 10 would return 1, being 1+0
and 977 would return 23, being 9+7+7

I’ve commented out some of my attempts before thinking of charAt(0) and some n’s will have as many as four digits, maybe more if I don’t have to limit it, but the largest test case stops in the thousands. 997 I think, but an extra decimal for margin of error.

function isItTHREED(n) {
  //  https://www.thoughtco.com/how-to-determine-number-is-prime-2312518

   //  Try 3.  Take the number, and add the digits up, when those digits are divisible by 3, the number is not prime.
  //          Take 2469, those digits add up to 21, and 21 is divisible by 3, therefore 2469 is not a prime number.
console.log('3s',n);
  /*
  n = n.toString();
  n = n.split('');
  //num = num.split('');
  n = [n];
  console.log("num", n);
  */
  return n;
} //end of isItTHREED

isItTHREED(10); // should return 1
isItTHREED(977); // should return 23.

CodePen

filter by 2, 3, 4 & 5

And what is your question?

I was trying to word this right for a code review on StackExchange… I finally found something that’ll work, it just feels like I’m going the long way to get there. Surely there’s something already built into to javascript I’m overlooking to reduce the value of a string. Or should I be trying to turn it into an array of digits?
This is working, but feels bulky

I think that what you may be looking for is the reduce method.

function isItTHREED(n) {
    return n.toString().split("")
        .reduce((total, char) => total + Number(char) || 0, 0);
}

The last zero is the total that you start with, and the second to last zero is the default number to use when the char isn’t a digit.

The function can also be written as two separate functions, to help make it easier to understand:

function sum(total, char) {
    return total + Number(char) || 0;
}
function isItTHREED(n) {
    return n.toString().split("")
        .reduce(sum, 0);
}
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.