Alt-Rock Ninja Cowgirl Alt-Rock Ninja Cowgirl - 19 days ago 7
Javascript Question

Split negative number apart and then sum together

i'm trying to write a function to sum the individual digits of a negative and positive number. I get stuck on how to sum the negative number after I've split the digits apart. Can I escape the '-' sign to have (-538) return

['-5', '3', '8' ]
instead of
[ '-', '5', '3', '8' ]
or am I going about the wrong way of solving this problem?



function sumDigits(num) {
var count = 0;

var intermediate = num.toString().split('')

for(var i = 0; i < intermediate.length; i++){
count += parseInt(intermediate[i])

}
return count;
}


var positive = sumDigits(2309);
console.log(positive); // --> 14


var negative = sumDigits(-8525);
console.log(negative); // --> 4




Answer

Use String#match with regex which matches optional - with the digit.

function sumDigits(num) {
  var count = 0;
  var intermediate = num.toString().match(/-?\d/g);
  for (var i = 0; i < intermediate.length; i++) {
    count += parseInt(intermediate[i])
  }
  return count;
}


var positive = sumDigits(2309);
console.log(positive);


var negative = sumDigits(-8525);
console.log(negative);