Sum a negative number (negative and positive digits) - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in a negative integer and returns the sum of its digits

For example −

-234 --> -2 + 3 + 4 = 5
-54  --> -5 + 4 = -1

Let’s write the code for this function −

Example

Following is the code −

const num = -4345;
const sumNum = num => {
   return String(num).split("").reduce((acc, val, ind) => {
      if(ind === 0){
         return acc;
      }
      if(ind === 1){
         acc -= +val;
         return acc;
      };
      acc += +val;
      return acc;
   }, 0);
};
console.log(sumNum(num));

Output

Following is the output in the console −

8
raja
Published on 14-Sep-2020 17:21:46
Advertisements