how to use the orderby function from the lodash library in typescript

To use the orderBy function from the lodash library in a TypeScript project, you first need to install and import the lodash library.

index.ts
npm install lodash
19 chars
2 lines
index.ts
import * as _ from 'lodash';
29 chars
2 lines

The orderBy function takes three parameters: the collection to be sorted, the iteratees or sorting rules, and the orders or the direction of sorting, which can be "asc" for ascending or "desc" for descending.

index.ts
_.orderBy(collection, [iteratees], [orders]);
46 chars
2 lines

Here's an example of using the orderBy function to sort an array of objects by a specific property:

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

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

const sortedPeople = _.orderBy(people, ['age'], ['asc']);

console.log(sortedPeople);
259 chars
15 lines

This will output:

index.ts
[
  { name: 'Bob', age: 25 },
  { name: 'Charlie', age: 30 },
  { name: 'Alice', age: 35 }
]
93 chars
6 lines

gistlibby LogSnag