How to Calculate the Sum of an Array in TypeScript?

As a TypeScript developer working on a project, I recently encountered a scenario where I needed to sum up the values of an array. In this tutorial, I will explain how to calculate the sum of an array in TypeScript. This is a common task in many applications, such as calculating total sales, aggregating data, or generating reports. Let me show you how to do this.

Calculate the Sum of an Array in TypeScript

Suppose you have an array of numbers representing the monthly sales figures for a company based in the United States. For example:

const monthlySales: number[] = [5200, 7800, 4500, 6300, 9100, 7600, 6800, 5900, 8200, 6100, 7300, 9400];

Your task is to calculate the total sales for the year by summing up all the values in the monthlySales array.

Let me show you different methods to achieve this.

Approach 1: Using a For Loop

One straightforward approach to calculate the sum of an array in TypeScript is to use a traditional for loop. Here’s an example:

function calculateTotalSales(sales: number[]): number {
  let total = 0;
  for (let i = 0; i < sales.length; i++) {
    total += sales[i];
  }
  return total;
}

const totalSales = calculateTotalSales(monthlySales);
console.log(`The total sales for the year is $${totalSales}.`);

In this approach, we define a function called calculateTotalSales that takes an array of numbers as input. We initialize a variable total to keep track of the running sum. We then iterate over each element of the array using a for loop and add it to the total variable. Finally, we return the total sum.

I executed the above TypeScript code using VS code, and you can see the exact output in the screenshot below:

Calculate the Sum of an Array in TypeScript

Check out Reverse an Array in TypeScript

Approach 2: Using the reduce() Method

TypeScript, being a superset of JavaScript, provides built-in methods for working with arrays. One such method is reduce(), which allows us to perform a reduction operation on an array.

Here’s how we can use reduce() to calculate the sum:

const monthlySales: number[] = [5200, 7800, 4500, 6300, 9100, 7600, 6800, 5900, 8200, 6100, 7300, 9400];
const totalSales = monthlySales.reduce((sum, current) => sum + current, 0);
console.log(`The total sales for the year is $${totalSales}.`);

The reduce() method takes a callback function as an argument, which receives two parameters: the accumulator (sum) and the current element (current).

The callback function is executed for each element in the array, and the result is accumulated in the sum variable. The second argument to reduce() is the initial value of the accumulator, which is set to 0 in this case.

Here is the exact output in the screenshot below:

TypeScript Calculate the Sum of an Array

Read Clear an Array in TypeScript While Preserving Its Type

Handle Different Data Types

In the examples above, we assumed that the array contains only numbers. However, you might notice arrays with mixed data types in many scenarios. TypeScript’s type system can help us handle such cases. Let’s consider an example where we have an array of objects representing sales data:

interface SalesData {
  month: string;
  amount: number;
}

const salesData: SalesData[] = [
  { month: 'January', amount: 5200 },
  { month: 'February', amount: 7800 },
  // ... more data
];

To calculate the total sales, we can use the reduce() method along with type assertions:

const totalSales = salesData.reduce((sum, current) => sum + current.amount, 0);
console.log(`The total sales for the year is $${totalSales}.`);

Here, we access the amount property of each object in the salesData array to calculate the sum. TypeScript’s type system ensures that we only access valid properties of the objects.

Check out Find the Length of an Array in TypeScript

Calculate the Sum of an Array in TypeScript with Conditions

Sometimes, you might need to calculate the sum based on certain conditions. For example, let’s say you want to calculate the total sales only for the months where the sales exceeded $7000. Here’s how you can achieve that:

const totalHighSales = monthlySales.reduce((sum, current) => {
  if (current > 7000) {
    return sum + current;
  }
  return sum;
}, 0);
console.log(`The total sales for months with high sales is $${totalHighSales}.`);

In this case, we modify the callback function of reduce() to include a condition. If the current sales amount exceeds $7000, we add it to the sum; otherwise, we skip it and return the current sum.

Check out Remove an Item from an Array in TypeScript

Performance Considerations

When working with large arrays in TypeScript, performance becomes a crucial factor. While the reduce() method is concise and expressive, it may not always be the most efficient approach. In such cases, a traditional for loop or a for-of loop might provide better performance.

Here’s an example using a for-of loop:

function calculateTotalSales(sales: number[]): number {
  let total = 0;
  for (const amount of sales) {
    total += amount;
  }
  return total;
}

The for-of loop iterates over each element of the sales array directly, without the need for indexing. This can lead to more readable and efficient code, especially when dealing with large datasets.

Conclusion

In this tutorial, I have explained different approaches to calculate the sum of an array in TypeScript. You can choose to use a traditional for loop, the reduce() method, or a for-of loop to sum array values in TypeScript.