how to sort by two keys using lodash in typescript

To sort an array by two keys using lodash in TypeScript, you can use the orderBy() function. The orderBy() function takes two arguments: the first argument is the array of items to be sorted, and the second argument is an array of sort predicates, which can be either a string or a function.

Here is an example of how to sort an array of objects by two keys, using lodash in TypeScript:

index.ts
import { orderBy } from 'lodash';

interface Person {
  firstName: string;
  lastName: string;
  age: number;
}

const people: Person[] = [
  { firstName: 'John', lastName: 'Doe', age: 30 },
  { firstName: 'Jane', lastName: 'Doe', age: 25 },
  { firstName: 'John', lastName: 'Smith', age: 40 },
  { firstName: 'Jane', lastName: 'Smith', age: 35 }
];

const sortedPeople = orderBy(
  people,
  [person => person.lastName, person => person.firstName],
  ['asc', 'asc']
);

console.log(sortedPeople);
/*
[
  { firstName: 'Jane', lastName: 'Doe', age: 25 },
  { firstName: 'John', lastName: 'Doe', age: 30 },
  { firstName: 'Jane', lastName: 'Smith', age: 35 },
  { firstName: 'John', lastName: 'Smith', age: 40 },
]
*/
716 chars
31 lines

In this example, we are sorting an array of Person objects by the lastName and firstName properties, in ascending order for both keys. The orderBy() function returns a new array with the sorted items.

gistlibby LogSnag