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
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.
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:
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.
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
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