I'm working on some practice problems using higher- order functions and while I was able to solve this problem. I can't help but think this code is ugly and not the most eloquent it could be. Is there a way to combined map and reduce is a cleaner way than I have done ? Additionally, is there any other methods or improvements I could have used here ? I'm just looking to get better and any feedback would be appreciated.
Problem: Given a number, "sumDigits" returns the sum of all its digits.If the number is negative, the first digit should count as negative.
function sumDigits(num) {
//create array of number char
var string = num.toString().split('');
//if first char is negative symbol let the first numeric element be negative
if (string[0] === "-") {
string[1] = '-' + string[1];
string.shift();
}
//convert string to int
var toInteger = string.map(function(x) {
return Number(x);
});
//get sum
return toInteger.reduce(function(sum, current) {
sum += current;
return sum;
})
}
sumDigits(-316);