JavaScript Program of Absolute Sum of Array Elements

Using JavaScript, one can find the absolute sum of all elements present in an array. Below is an example to understand the problem clearly.

Example:

Input: [ -4, -7, 3, 10, 12] 
Output: 36
Explanation: Absolute values: 4 + 7 + 3 + 10 + 12 = 36

There are several approaches for finding the absolute sum of array elements using JavaScript which are as follows:

Table of Content

  • Brute Force Approach
  • Using Array.reduce() method
  • Using Array.forEach() Method

Brute Force Approach

Declare a function which takes an array as its parameter and initialize a variable sum to store the sum of absolute values of array elements. Use a for loop to iterate through each element of the array. Inside the loop, use the Math.abs() function to get the absolute value of each element and add it to the sum variable. Return the final sum.

Example: To demonstration finding absolute sum of array elements using brute force approach.

JavaScript
function absoluteSumIterative(arr) {
    let sum = 0;
    for (let i = 0; i < arr.length; i++) {
        sum += Math.abs(arr[i]);
    }
    return sum;
}

const arr = [-4, -7, 3, 10, 12];
console.log("Absolute sum (iterative) is:", absoluteSumIterative(arr));

Output
Absolute sum (iterative) is: 36

Time complexity: O(n)

Space complexity: O(1)

Using Array.reduce() method

Declare a function which takes an array as its parameter. Use the reduce() method on the input array arr. Inside the reduce() method, accumulate the sum by adding the absolute value of each element (Math.abs(num)) to the accumulator (sum). Start with an initial value of 0 for the accumulator. Return the final accumulated sum.

Example: Demonstration of finding Absolute sum of array elements using Array.reduce().

JavaScript
function absoluteSumReduce(arr) {
    return arr
    .reduce((sum, num) => sum + Math.abs(num), 0);
}

const arr = [-4, -7, 3, 10, 12];
console.log("Absolute sum (reduce) is:", absoluteSumReduce(arr));

Output
Absolute sum (reduce) is: 36

Time complexity: O(n)

Space complexity: O(1)

Using Array.forEach() Method

Declare a function that takes an array as its parameter. Initialize a variable sum to store the sum of the absolute values of the array elements. Use the forEach() method to iterate through each element of the array. Inside the forEach() method, use the Math.abs() function to get the absolute value of each element and add it to the sum variable. Return the final sum.

Example: To demonstrate finding the absolute sum of array elements using the forEach() method.

JavaScript
function absoluteSumForEach(arr) {
    let sum = 0;
    arr.forEach(num => {
        sum += Math.abs(num);
    });
    return sum;
}

const arr = [-4, -7, 3, 10, 12];
console.log("Absolute sum (forEach) is:", absoluteSumForEach(arr));

Output
Absolute sum (forEach) is: 36

Time Complexity: O(n)

Space Complexity: O(1)



Contact Us