how to use the orderby function from lodash in javascript

To use the orderBy function from lodash, first we need to install it via npm:

index.tsx
npm install lodash
19 chars
2 lines

Then, we can import it into our .js file:

index.tsx
const _ = require('lodash');
29 chars
2 lines

Now, we can use the orderBy function to sort an array. Here's an example:

index.tsx
// Sample array of objects
const people = [
  { name: 'John', age: 30 },
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 35 },
];

// Sort by name
const sortedByName = _.orderBy(people, ['name']);
console.log(sortedByName);

// Sort by age descending
const sortedByAge = _.orderBy(people, ['age'], ['desc']);
console.log(sortedByAge);
339 chars
15 lines

In the first example, we use ['name'] as the first argument to sort by the name property. In the second example, we use ['age'] as the first argument and ['desc'] as the second argument to sort by the age property in descending order.

Note that lodash's orderBy can handle multiple properties and sort orders. For instance, we can sort by multiple keys:

index.tsx
const sortedByKey = _.orderBy(people, ['age', 'name'], ['asc', 'desc']);
console.log(sortedByKey);
99 chars
3 lines

Here, we sort by age first in ascending order, and then by name in descending order.

gistlibby LogSnag