Search code examples
javascriptarrayssumdigits

Return sum of a number (positive or negative)


I need to make a function that takes a number and returns sum of it's digits, if the number is negative the first digit should be considered negative when adding numbers, this is what I have:

var arrx = [];
var oper;
var others = 0;

function sumDigits(num) {
    // your code here
    var y = num.toString();
    var c = y.split("");
    c.forEach((h) => arrx.push(Number(h)) );
    if (num < 0){
        oper = -arrx[0];
        for (var z = 1; z < arrx.length; z++){
            others += arrx[z];
        }

        return others + oper;
    }

    return arrx.reduce((a,b) => a+b);
}

sumDigits(1234);

When given negative number, function returns NaN, what's the problem ?


Solution

  • Use optimized and short version of sumDigits() function:

    function sumDigits(num) {
      var isNeg = num < 0,   // check whether the number is negative
          numbers = (isNeg? String(num).slice(1) : String(num)).split('').map(Number);
      if (isNeg) numbers[0] *= -1;   // 'recovering' the number's sign
    
      return numbers.reduce(function(a,b){ return a + b; });
    }
    
    console.log(sumDigits(1234));
    console.log(sumDigits(-951));