parseInt and map(Number)...what's the difference really?

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?

They aren’t the same code. What that map is doing is the same thing you do on each iteration with parseInt() - but the data being fed into reduce is broken.

1 Like