Taking the absolute sum of Array of Numbers in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in an array with both positive and negative numbers and returns the absolute sum of all the elements of the array. We are required to do this without taking help of any inbuilt library function.

For example: If the array is −

const arr = [1, -5, -34, -5, 2, 5, 6];

Output

Then the output should be −

58

Therefore, let’s write the code for this function −

Example

The code for this will be −

const arr = [1, -5, -34, -5, 2, 5, 6];
const absoluteSum = arr => {
   let res = 0;
   for(let i = 0; i < arr.length; i++){
      if(arr[i] < 0){
         res += (arr[i] * -1);
         continue;
      };
      res += arr[i];
   };
   return res;
};
console.log(absoluteSum(arr));

Output

The output in the console will be −

58
raja
Published on 17-Oct-2020 14:52:03
Advertisements