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?

Your split delimiter is different in the first, but that may not be the total issue, because I have not tested the code (as I don’t know what the challenge instructions are or what test cases are possible).

1 Like

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