I was working on an algorithm on Codewars and I’m confused as to why one form of the code worked as opposed to another.
The following code did not work.
function sumDigits(number){
number = Math.abs(number);
let num = number.toString().split(' ').reduce((a,b)=>{return (a)+parseInt(b)});
return num;
}
I found this slightly different code on StackOverflow that did:
function sumDigits(number) {
number = Math.abs(number);
let sum = number.toString().split('').map(Number).reduce((a,b)=>{return a+b},0)
return sum;
}
Why did map(Number) produce an answer whereas .reduce((a,b)=>return parseInt(a)+parseInt(b)})
did not?