Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript and array reduce function

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.

like image 744
Tom Avatar asked Dec 30 '12 01:12

Tom


People also ask

What is array reduce in TypeScript?

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.

How do you reduce a function in an array of objects?

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);

How do you write reduce in TypeScript?

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!

What is the use of reduce in TypeScript?

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.


2 Answers

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[]>[]) 
like image 198
Quentin 2 Avatar answered Sep 26 '22 06:09

Quentin 2


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.

like image 36
JohnnyHK Avatar answered Sep 26 '22 06:09

JohnnyHK