Do you know what the reduce
array method does in TypeScript? Can you provide a simple example of usage?
I searched on Google and the TypeScript language specification but could not find any decent explanation and examples.
Array.prototype.reduce() The reduce() method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.
The reduce() method executes the function for each value of the array (non-empty array) from left to right. The reduce() method has the following syntax: let arr = [];arr. reduce(callback(acc, curVal, index, src), initVal);
Use a generic to type the reduce() method in TypeScript, e.g. const result = arr. reduce<Record<string, string>>(myFunction, {}) . The generic is used to specify the type of the return and initial values of the reduce() method. Copied!
Master Typescript : Learn Typescript from scratch reduce() method applies a function simultaneously against two values of the array (from left-to-right) as to reduce it to a single value.
Just a note in addition to the other answers.
If an initial value is supplied to reduce then sometimes its type must be specified, viz:-
a.reduce(fn, [])
may have to be
a.reduce<string[]>(fn, [])
or
a.reduce(fn, <string[]>[])
It's actually the JavaScript array reduce
function rather than being something specific to TypeScript.
As described in the docs: Apply a function against an accumulator and each value of the array (from left-to-right) as to reduce it to a single value.
Here's an example which sums up the values of an array:
let total = [0, 1, 2, 3].reduce((accumulator, currentValue) => accumulator + currentValue); console.log(total);
The snippet should produce 6
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With