how to use the reduce function from the underscore library in typescript

To use the reduce() function from the Underscore library in TypeScript, you need to first install the library using npm. You can do this by running the following command in your terminal:

index.ts
npm install underscore
23 chars
2 lines

Once the library is installed, you can import it into your TypeScript file and use the reduce() function as shown below:

index.ts
import * as _ from 'underscore';

const numbers: number[] = [1, 2, 3, 4, 5];

// without generics
const sum: number = _.reduce(numbers, (accumulator: number, currentValue: number) => {
  return accumulator + currentValue;
}, 0);

console.log(sum); // Output: 15


// with generics
interface Person {
  name: string;
  age: number;
  gender: string;
}

const people: Person[] = [
  { name: 'John', age: 25, gender: 'male' },
  { name: 'Sarah', age: 30, gender: 'female' },
  { name: 'Mark', age: 20, gender: 'male' },
];

const totalAge: number = _.reduce<Person, number>(people, (accumulator: number, currentValue: Person) => {
  return accumulator + currentValue.age;
}, 0);

console.log(totalAge); // Output: 75
714 chars
31 lines

In the example above, we first imported the Underscore library using the import statement. We then declared an array of numbers and an array of objects of type Person.

We then used the reduce() function to calculate the sum of all the numbers in the numbers array, and the total age of all the people in the people array.

Note that when using the reduce() function with TypeScript, it is good practice to pass the generic types T and R to ensure type safety. In the example above, we passed the Person type as the generic type T, and the number type as the generic type R.

gistlibby LogSnag