# How to get total number from a number string using reduce?

like on the question’s title: how to get a total number from a string of numbers using reduce? now I’m aware of other ways to get the result but I’m more interested to understand the reduce() more

to solve this I tried this

`total="1234"; console.log(total.split("").reduce((x,y) => y+=parseInt(x),Number(0))); `

``````"43210"
``````

the result was string, I tried parseInt() instead of Number() but the result was the same
also, I tried to remove the accumulator 0 but the result was string too

``````"4321"
``````

how to get the reduce accumulate the array values as ints?

I recommend another intermediate function, namely a `.map()`. So the part before the reduce call should be `total.split("").map(x => parseInt(x))`. I think you’ll find the reducer a bit less infuriating once you’re dealing with a sane type.

1 Like

Hi, it seems that you missed a parenthesis, because the acummulator 0 is being concatenated as the second argument of the console.log function, instead of being the second argument of the reduce function.

As I said, the only problem is a pair of parenthesis to agrupate the function paramether:

``````  total="1234";
console.log(total.split("").reduce(
((y,x)=> y+=parseInt(x)),Number(0)));

// 10
``````
``````const total="1234";
console.log([...total].reduce((sum, num) => sum += +num, 0)); // 10
``````

You also had your x and y parameters reversed. It is always better to name your variables in a way that describes what they represent. x and y do not describe anything and make it harder to see syntax and logic errors.

2 Likes

So put plus becides the array element would cast it to int?

1 Like

like up there how to get the same result with brute force way

``````var value = 2568,
sum = 0;

while (value) {
sum += value % 10;
value = Math.floor(value / 10);
}

console.log(sum);
``````

now how to do this on one line as return

one issue is here.
if I write `(acc, cur) => cur += parseInt(acc)` do you see the issue in the callback?

You could use recursion.

``````function sumDigits(num, sum = 0) {
return num
? sumDigits(Math.floor(num / 10), sum + num % 10)
: sum;
}
sumDigits(1234); // 10
``````

No, what is the issue on that?

you are using `parseInt` on the first parameter, the accumulator `acc`, which if you did things alright should already be a number, not on the current element of the array `cur`

I don’t know why that happens but return a “43210” string

the accumulator is the value returned from previous callback call
so, when `acc` “0”, `cur` is “1”
`cur + parseInt(acc)` is returned and `acc` becomes `"10"`, then `cur` is “2”, and now it is returned `"210"` and so on