-5

Let's suppose I have an integer value as

const num = 123456789

and I want to print the sum of these no. in react as 1+2+3+4+5+6+7+8+9 = 45

expect output = 45

approach I am following is as follows

const [total, setTotal] = useState(0);

const num = 123456789
for (const element of num ) {
   setTotal(total + element) 
}

console.log(total)

Output I am getting is : 01

Need your help here please!

NinjaTS
  • 79
  • 6

2 Answers2

4

You can continuously divide by 10 until the number becomes 0 and use % 10 to get the last digit.

let num = 123456789;
let sum = 0;
for (; num; num = Math.floor(num / 10)) 
  sum += num % 10;
console.log(sum);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
1

A one-liner

const num = 123456789
console.log(num.toString().split('').reduce((acc, elem) => elem*1+acc, 0))
JeanJacquesGourdin
  • 1,496
  • 5
  • 25