In this tutorial, I will explain how to effectively use the array reduce method in TypeScript. The reduce() method in TypeScript allows you to reduce an array to a single value by applying a callback function to each element. It is an iterative method that runs the callback function over all elements in the array in ascending index order in TypeScript.
Array Reduce() Method in TypeScript
The reduce method takes a “reducer” callback function as an argument, along with an optional initial value. The callback function is executed on each element of the array, and it receives four parameters:
- accumulator: The accumulated value that is returned from the previous iteration.
- currentValue: The current element being processed in the array.
- currentIndex (optional): The index of the current element being processed.
- array (optional): The array on which reduce was called.
Here’s a simple example to demonstrate the usage of reduce in TypeScript:
const numbers: number[] = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum); // Output: 15
In this example, we have an array of numbers and we use reduce to calculate the sum of all elements. The reducer function adds the current value to the accumulator on each iteration, starting with an initial value of 0.
Here is the exact output you can see in the screenshot below:

Check out How to Find an Object in a TypeScript Array?
Array Reduce() Method in TypeScript – Example
Imagine you have an array of objects representing sales data for different states in the USA. Each object contains the state name and the total sales amount. Your task is to group the sales data by state and calculate the total sales for each state.
interface SalesData {
state: string;
amount: number;
}
const salesData: SalesData[] = [
{ state: 'California', amount: 1500 },
{ state: 'New York', amount: 2000 },
{ state: 'California', amount: 1200 },
{ state: 'Texas', amount: 1800 },
{ state: 'New York', amount: 2500 },
];
const salesByState = salesData.reduce((accumulator, currentValue) => {
const { state, amount } = currentValue;
accumulator[state] = (accumulator[state] || 0) + amount;
return accumulator;
}, {} as Record<string, number>);
console.log(salesByState);
// Output: { California: 2700, 'New York': 4500, Texas: 1800 }
In this example, we use reduce to group the sales data by state. The reducer function checks if the state already exists in the accumulator object. If it does, it adds the current amount to the existing value; otherwise, it initializes the state with the current amount. The initial value of the accumulator is an empty object ({}).
Here is the exact output in the screenshot below:

Read How to Calculate the Sum of an Array in TypeScript?
Imitating SQL Aggregate Functions
The reduce method can also be used to imitate SQL aggregate functions like COUNT and SUM. Let’s consider an array of employee objects and perform some calculations.
interface Employee {
name: string;
department: string;
salary: number;
}
const employees: Employee[] = [
{ name: 'John Doe', department: 'IT', salary: 5000 },
{ name: 'Jane Smith', department: 'HR', salary: 4500 },
{ name: 'Michael Johnson', department: 'IT', salary: 5500 },
{ name: 'Emily Davis', department: 'Finance', salary: 6000 },
{ name: 'Robert Wilson', department: 'IT', salary: 5200 },
];
// Count the number of employees
const employeeCount = employees.reduce((count) => count + 1, 0);
console.log('Total employees:', employeeCount); // Output: Total employees: 5
// Calculate the total salary of all employees
const totalSalary = employees.reduce((sum, employee) => sum + employee.salary, 0);
console.log('Total salary:', totalSalary); // Output: Total salary: 26200
// Calculate the average salary
const averageSalary = totalSalary / employeeCount;
console.log('Average salary:', averageSalary); // Output: Average salary: 5240
In this example, we use reduce to count the number of employees by incrementing the count on each iteration. We also calculate the total salary by adding each employee’s salary to the sum. Finally, we calculate the average salary by dividing the total salary by the employee count.
Check out How to Reverse an Array in TypeScript?
Flattening Arrays in TypeScript
Another useful application of the reduce() method in TypeScript is flattening nested arrays into a single-level array. Let’s say we have an array of customer orders, where each order contains an array of purchased items.
Here is the complete code:
interface Order {
orderId: number;
items: string[];
}
const orders: Order[] = [
{ orderId: 1, items: ['Shirt', 'Jeans'] },
{ orderId: 2, items: ['Shoes', 'Socks'] },
{ orderId: 3, items: ['Hat', 'Gloves', 'Scarf'] },
];
const allItems = orders.reduce((items, order) => [...items, ...order.items], []);
console.log(allItems);
// Output: ['Shirt', 'Jeans', 'Shoes', 'Socks', 'Hat', 'Gloves', 'Scarf']
Here, we use reduce to flatten the nested arrays of items into a single array. The reducer function spreads the accumulated items array and the current order’s items array into a new array using the spread operator (…).
Conclusion
The array reduce() method in TypeScript allows you to perform various operations on arrays, such as aggregation, grouping, and flattening. In this tutorial, I explained how to use array Reduce() method in TypeScript with some examples.
I’m Bijay Kumar Sahoo, and I am honored to be awarded the Microsoft MVP. With over 18 years of experience in the IT industry, I got a chance to work on SharePoint Framework (SPFx) development, TypeScript, React, JavaScript, etc. My journey has taken me through esteemed organizations such as TCS, HP, and KPIT, where I have honed my skills and expanded my expertise. Check out more about me here.