Open In App

How to find the Sum of an Array of Numbers in JavaScript ?

Last Updated : 26 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Array in JavaScript is a data structure that is used to store a list of data. It is a contiguous block of memory which is used to store the data. As it is contiguous in memory we can access its elements in constant time.

There are several different methods for finding the sum of an array of numbers using JavaScript which are as follows:

Using for Loop

In this method, we will use a simple for loop and then iterate over the array. On each iteration, we will add the current element to the sum and then return the sum. To implement this algorithm we declare a variable sum to store the sum and then Loop through the array and at each iteration we add the current element to the sum to return the sum.

Example: To demonstrate using a traditional `for` loop to iterate through an array and calculate the sum of its elements.

Javascript




function sumArray(arr) {
    let sum = 0;
    for (let i = 0; i < arr.length; i++) {
        sum += arr[i];
    }
    return sum;
}
const arr = [2.3, 4.7, 4, 3];
console.log("Input:", arr);
console.log("Output:", sumArray(arr));


Output

Input: [ 2.3, 4.7, 4, 3 ]
Output: 14

Time complexity: O(N)
Space complexity: O(1)

Using reduce () Method

In this method we will use reduce() method. In this method we need to pass a callback function which takes four arguments. Accumulator(acc), Current value (curr) ,Current Index(optional), Source Array(optional). This method iterates through each element of the array and then callback function is called for each element. The accumulator will calculate the new value for accumulator based on the current element and its current value.

Example: To demonstrate using the `reduce` method to accumulate the sum of elements in a given array.

Javascript




function sumArray(arr) {
    return arr.reduce(function (acc, curr) {
        return acc + curr;
    }, 0);
}
const arr = [2.3, 4.7, 4, 3];
console.log("Input:", arr);
console.log("Output:", sumArray(arr));


Output

Input: [ 2.3, 4.7, 4, 3 ]
Output: 14

Time complexity: O(N)
Space complexity: O(1)

Using the eval() function

In this method we will use the eval() function. This method is used to evaluate the string. In this method we take take the string argument and then executes the given operation.

Example: To demonstrate utilizing the `join` method and `eval` function to dynamically calculate the sum of elements in a given array.

Javascript




function sumArray(arr) {
 
    let expression = arr.join('+');
    return eval(expression);
}
 
const arr = [2.3, 4.7, 4, 3];
console.log("Input:", arr);
console.log("Output:", sumArray(arr));


Output

Input: [ 2.3, 4.7, 4, 3 ]
Output: 14

Time complexity: O(N)
Space complexity: O(N)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads