Working on some practice problems involving higher-order functions, I managed to solve this particular problem. However, the code I used feels somewhat messy and not as elegant as it could be. Is there a better way to combine map and reduce for a cleaner solution? In addition, are there any other methods or optimizations that could have been employed here? Seeking feedback to improve my skills further.
Here is the problem: Given a number, the function "sumDigits" returns the sum of all its digits. If the number is negative, the first digit should be treated as negative.
function sumDigits(num) {
// Create an array of number characters
var string = num.toString().split('');
// If the first character is a negative symbol, make the first numeric element negative
if (string[0] === "-") {
string[1] = '-' + string[1];
string.shift();
}
// Convert the string to integers
var toInteger = string.map(function(x) {
return Number(x);
});
// Get the sum
return toInteger.reduce(function(sum, current) {
sum += current;
return sum;
})
}
sumDigits(-316);