Big blue ball

Sum of an array of numbers in JavaScript or TypeScript

This article will show you how to calculate the sum of all elements in an array of numbers. Such an operation is very simple. You just have to iterate over all the elements in the array and make a sum of all values.

However, as you probably know, the JavaScript and TypeScript languages are sometimes complex. There are various different functions and operators available that can do the same thing.

As a result, this guide contains many different methods that you can try to use in your web application. You may review each sample and find the solution that is most suitable in your case.

Using the reduce method in JavaScript

The JavaScript language already provides a very nice function that allows you to calculate the sum of all integers in an array. The Array object contains the reduce() method. To use it, you have to pass a callback that will be executed for each element of an array. Also, the callback accepts two parameters, the value to store the sum and the current value.

It is worth mentioning that you may need to supply the default value. In our case it may be the number 0. Finally, our callback has to perform some mathematical operation.

Please see the following example. It shows how to use the reduce() method in the code.

const values = [1, 2, 3, 4, 5];

const sumOfValues = values.reduce((accumulation, current) => {
    return accumulation + current;
}, 0);

console.log(sumOfValues);

If you run the above sample, the console should contain the number 15. It's the sum of all values in the given array.

Function that calculates sum of elements in array

To avoid code duplication, you may create a special function that will calculate the sum of all elements in an array. Then, you can reuse that function in any part of your project. Also, you may choose a meaningful name for that function, so it is easy to read the code and understand what that function is intended to do. In our specific case the name will be calculateSumOfElements.

Now, you can see our code sample.

function calculateSumOfElements(values) {
    return values.reduce((accumulation, current) => {
        return accumulation + current;
    }, 0);
}

const values = [1, 2, 3, 4, 5];

const sumOfValues = calculateSumOfElements(values);

console.log(sumOfValues);

After the calculation, the console should contain the number 15.

Sum of specific property of an element

If you are building a complex application, then you may not always be able to obtain a plain array of integers. The data may be sent over the network inside of a complex structure. The supplied array may contain a list of objects.

As a result, you may want to calculate a sum of a specific property that belongs to each element. That is also possible, but it requires a small modification to the code. You need to use the map() method that will create a new array that consists of only values taken from that single property.

Please see below our example of how this can be done in the JavaScript language.

const values = [{value: 1}, {value: 2}, {value: 3}, {value: 4}, {value: 5}];

const sumOfValues = values.map(item => item.value).reduce((accumulation, current) => {
    return accumulation + current;
}, 0);

console.log(sumOfValues);

The browser console will contain number 15 after executing the above code.

Using the reduce method in TypeScript

It is worth noting that the reduce() method may also be used in a TypeScript application. However, you may want to add several changes to the code. Please see the following sample, we are using the number type there.

const values: number[] = [1, 2, 3, 4, 5];

const sumOfValues: number = values.reduce((accumulation, current) => {
    return accumulation + current;
}, 0);

console.log(sumOfValues);

Finally, the console will contain number 15 after running the given code.

Using generic type in TypeScript for the reduce method

There may be a much more complicated situation when you are making code in TypeScript language. For example, the code may use custom structures and the reduce() method may need to return data in specific format.

However, that should not be an issue at all. You can use the generic type to specify how the data should look. Please review the following sample to see how the ArraySum type is passed into the reduce() method.

type ArraySum = {
    value: number
};

const values: number[] = [1, 2, 3, 4, 5];

const sumOfValues: ArraySum = values.reduce<ArraySum>((accumulation, current) => {
    return { value: accumulation.value + current };
}, { value: 0 });

console.log(sumOfValues);

Now, the console output may be a little different. There will be an object with a calculated value inside.

{ value: 15 }

TypeScript class that allows to get sum of numbers in array

In case if you are building an object-oriented application, you may want to have a special class that allows you to calculate the sum of elements. Sometimes, this may be very useful, since the class may encapsulate all functionality related to calculation of the sum.

As a result, we've created a sample code that you may use to solve your needs. The ArraySumProducer class has a constructor that accepts an array of elements. Also, there is a public calculate() function that produces the required sum of all the elements.

You can see the source code here:

class ArraySumProducer {
    constructor(private values: number[]) { }

    public function calculate() {
        return this.values.reduce((accumulation, current) => {
            return accumulation + current;
        }, 0);
    }
}

const values: number[] = [1, 2, 3, 4, 5];

const sumProducer: number = new ArraySumProducer(values);

const sumOfValues = sumProducer.calculate();

console.log(sumOfValues);

As usually, the console will contain number 15 after running the given code.

Using the for..of loop

You may also consider using the classical algorithm of calculating a sum of a collection of numbers. The JavaScript language provides the for..of loop that allows us to iterate over all elements in an array. Then, on each iteration, you can add current value to the total sum.

Please see below how this algorithm can be implemented.

const values = [1, 2, 3, 4, 5];

let sumOfValues = 0;

for (const singleValue of values) {
    sumOfValues += singleValue;
}

console.log(sumOfValues);

The console will contain number 15 after executing the given code.

Using the forEach method

There is another way to iterate over all elements in an array. You may also use the forEach() method to calculate the sum of all values. The difference is that you have to pass a callback into that function. Then, the callback can add a current value to the total sum.

Please see below how it can be done.

const values = [1, 2, 3, 4, 5];

let sumOfValues = 0;

values.forEach(singleValue => {
    sumOfValues += singleValue;
});

console.log(sumOfValues);

Finally, the console should contain the number 15 if you run the above code in a browser or in a NodeJS application.

Using the for loop

If you need more flexibility, then you can try using the regular for loop to calculate the sum of all elements in an array. But, you'll have to create an index variable and increment it manually on each iteration. Please see the code sample below.

const values = [1, 2, 3, 4, 5];

let sumOfValues = 0;

for (let index = 0; index < values.length; index++) {
    sumOfValues += values[index];
}

console.log(sumOfValues);

This method can be helpful if you need to control how the loop is iterated. Also, after running the above code, the console should contain the number 15.

Using the while loop

If for some reason the for loop is not acceptable for you. Then you may also try to use the while loop to make a sum of all numbers in the array. The algorithm is given below.

const values = [1, 2, 3, 4, 5];

let sumOfValues = 0;
let index = 0;

while (index < values.length) {
    sumOfValues += values[index];

    index++;
}

console.log(sumOfValues);

As you see there, you also have to manually increment the index variable on each iteration. And the console should contain number 15 if you run the given demo.

Using the map() method

The other option to calculate a sum of all numbers is to use the map() method. However, this solution may not be suitable in all cases, since the map() function creates a new array. But, if you already use this method in your code for some purposes, then you can consider calculating a sum of elements in a callback for the map() function.

Please see below our code sample.

const values = [1, 2, 3, 4, 5];

let sumOfValues = 0;

values.map(singleValue => {
    sumOfValues += singleValue;
});

console.log(sumOfValues);

The same as for other code samples, the console should contain number 15 if you run the given demo.

Which method to use?

As you see, most of the algorithms are similar. However, you may not be sure which method to use in the code. If the array of numbers is small, then you may consider using the method which is small and easy to maintain.

On another hand, if the array of numbers is large and contains many records, you may consider using the regular for or while loops. However, it's hard to predict which method is the fastest. It totally depends on data, system configuration and system environment.

The good idea is to measure execution time for each method. You may write several samples, test them and choose the solution that is the most applicable.

Conclusion

It's very easy to calculate a sum of all elements in an array. JavaScript and TypeScript languages already provide the reduce() method that can be used for that purpose. If for some reason, the reduce() method is not acceptable, then the other option is to use the for..of loop.

As an alternative, it's also possible to use the forEach loop for iterating over a list of numbers. In addition, you may also consider using the for or while loops. However, in that case, you have to keep and increment the index value yourself.

Related Articles

Big white clock

How to get a Unix timestamp in JavaScript or TypeScript language

Front end code

Checking if a variable exists in JavaScript or TypeScript

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *