reduce in typescript

In TypeScript, the reduce method is available on arrays and can help you perform operations on the elements of an array and collect the result into a single value.

Here's an example of a simple use case, where we use reduce to sum all the elements of an array:

index.ts
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);

console.log(sum); // Output: 15
156 chars
5 lines

In the code above, we pass a lambda function to the reduce method, which takes two arguments: the accumulator and the currentValue. The accumulator is initialized to 0, which is the second argument passed to reduce.

For more advanced use cases, the reduce method can also take an optional generic parameter, which specifies the type of the result. For example, here's how you can use reduce to find the maximum number in an array:

index.ts
const numbers = [1, 5, 3, 4, 2];
const max = numbers.reduce<number>((prev, current) => prev > current ? prev : current);

console.log(max); // Output: 5
153 chars
5 lines

In this case, we specify the type of the result as number by passing it as a generic argument to the reduce method. The lambda function passed to reduce compares the previous and current values and returns the maximum.

So, if you need to perform operations on arrays and collect the result into a single value, the reduce method in TypeScript is a powerful tool to have in your toolkit.

gistlibby LogSnag