乐闻世界logo
搜索文章和话题

How to make Lodash sortBy() to sort data to descending order?

1个答案

1

In JavaScript, the Lodash library provides a convenient method sortBy() for sorting arrays. By default, sortBy() sorts data in ascending order. If you need to sort data in descending order, you can chain the reverse() method after using sortBy().

I'll demonstrate this with an example using _.sortBy() combined with reverse() to sort in descending order.

Assume we have the following array containing employee objects, each with name and salary properties:

javascript
const employees = [ { name: 'Tom', salary: 50000 }, { name: 'Sally', salary: 80000 }, { name: 'John', salary: 60000 }, { name: 'Mike', salary: 90000 } ];

If we want to sort this array in descending order based on salary (salary), we can first use _.sortBy() to sort in ascending order by salary, then apply .reverse() to reverse the array, achieving descending order. Here's the code:

javascript
import _ from 'lodash'; const sortedEmployees = _.sortBy(employees, 'salary').reverse(); console.log(sortedEmployees);

After executing this code, the output of sortedEmployees will be as follows, indicating that the data has been sorted in descending order by salary:

plaintext
[ { name: 'Mike', salary: 90000 }, { name: 'Sally', salary: 80000 }, { name: 'John', salary: 60000 }, { name: 'Tom', salary: 50000 } ]

This is one way to use Lodash's sortBy() and reverse() methods to sort arrays in descending order. It's simple and effective, especially useful when you need to quickly sort data by a specific field in descending order.

2024年6月29日 12:07 回复

你的答案