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.ts156 chars5 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.ts153 chars5 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