how to use the sortby function from lodash in javascript

To use _.sortBy() function of lodash library in JavaScript, you need to follow these steps:

  1. Import lodash library in your JavaScript file as shown below (assuming lodash is installed using npm).
index.tsx
const _ = require('lodash');
29 chars
2 lines
  1. Create an array of objects that needs to be sorted. Assume that we have an array users containing multiple objects as shown below:
index.tsx
const users = [
  {id: 1, name: 'John', age: 29},
  {id: 2, name: 'Alex', age: 25},
  {id: 3, name: 'Mary', age: 32},
  ....
];
128 chars
7 lines
  1. Use _.sortBy() function to sort the array based on the property of an object. For example, to sort the array based on the age property of an object, use the following code:
index.tsx
const usersByAge = _.sortBy(users, 'age');
43 chars
2 lines

This will return a new sorted array of users based on their age in ascending order.

  1. If you want to sort the array in descending order, you can pass a sorting function instead of a property name as shown below:
index.tsx
const usersByAgeDesc = _.sortBy(users, user => -user.age);
59 chars
2 lines

This will return a new sorted array of users based on their age in descending order.

Note: The original array remains unchanged after using the sortBy() function.

gistlibby LogSnag