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

To use the pluck function in TypeScript, you first need to install the Underscore library and include it in your project:

index.ts
npm install underscore
23 chars
2 lines

Then, you can import the function in your TypeScript file:

index.ts
import { pluck } from 'underscore';
36 chars
2 lines

The pluck function takes two arguments: an array of objects and the name of the property you want to extract from each object. It returns an array of the extracted values.

Here's an example usage:

index.ts
interface Person {
  name: string;
  age: number;
}

const people: Person[] = [
  { name: 'Alice', age: 30 },
  { name: 'Bob', age: 25 },
  { name: 'Charlie', age: 40 },
];

const names: string[] = pluck(people, 'name'); // ['Alice', 'Bob', 'Charlie']
const ages: number[] = pluck(people, 'age'); // [30, 25, 40]
313 chars
14 lines

Note that Underscore is a functional programming library that provides many useful functions for working with arrays, objects, and functions. If you're familiar with or interested in functional programming, it's worth exploring Underscore and other similar libraries like Lodash.

gistlibby LogSnag