Absolute sum of array elements - 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];

Then the output should be −

58

Example

Following is the code −

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

Following is the output in the console −

58

Updated on: 16-Sep-2020

533 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements