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

To use the sortBy function from the Underscore library in TypeScript, you first need to reference the Underscore library in your TypeScript file. This can be done using the import statement, like so:

index.ts
import * as _ from 'underscore';
33 chars
2 lines

Once you have the Underscore library referenced, you can use the sortBy function to sort an array based on a specific property. The sortBy function takes two parameters: the first parameter is the array you want to sort, and the second parameter is a function that returns the value you want to sort by.

Here's an example of using sortBy in TypeScript to sort an array of objects based on a property called firstName:

index.ts
interface Person {
  firstName: string;
  lastName: string;
}

const people: Person[] = [
  { firstName: 'John', lastName: 'Doe' },
  { firstName: 'Jane', lastName: 'Doe' },
  { firstName: 'Bob', lastName: 'Smith' },
];

const sortedPeople = _.sortBy(people, (person) => person.firstName);

console.log(sortedPeople);
318 chars
15 lines

In this example, we first define an interface called Person to represent the objects in our array. We then define an array of Person objects called people. We use the sortBy function to sort this array based on the firstName property of each Person object. The sorted array is then stored in a variable called sortedPeople, which we log to the console.

Output:

index.ts
[
  { firstName: 'Bob', lastName: 'Smith' },
  { firstName: 'Jane', lastName: 'Doe' },
  { firstName: 'John', lastName: 'Doe' }
]
130 chars
6 lines

gistlibby LogSnag