Taking the absolute sum of Array of Numbers in JavaScript


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

Updated on: 17-Oct-2020

372 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements