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

How to Sort items in an array by more than one field with lodash

1个答案

1

When sorting an array by multiple fields with Lodash, the _.orderBy function is used. This function enables you to define the fields for sorting and the order (ascending or descending) for each field. Below, I'll illustrate this with a specific example.

Consider an array of employee objects, each containing properties like name, age, and hireYear. We'll sort by age in ascending order first, and for matching ages, by hireYear in descending order.

First, import the Lodash library:

javascript
const _ = require('lodash');

Then, assume the following array:

javascript
let employees = [ { name: "John Doe", age: 25, hireYear: 2017 }, { name: "Jane Smith", age: 25, hireYear: 2015 }, { name: "Alicia Keys", age: 30, hireYear: 2010 }, { name: "James Brown", age: 30, hireYear: 2012 } ];

Use _.orderBy to sort this array:

javascript
let sortedEmployees = _.orderBy(employees, ['age', 'hireYear'], ['asc', 'desc']);

In this example, ['age', 'hireYear'] specifies the sorting sequence: first by age ascending, and if ages match, then by hireYear descending. The array ['asc', 'desc'] defines the sort order for each respective field.

Display the sorted output:

javascript
console.log(sortedEmployees);

The output will be:

json
[ { "name": "Jane Smith", "age": 25, "hireYear": 2015 }, { "name": "John Doe", "age": 25, "hireYear": 2017 }, { "name": "James Brown", "age": 30, "hireYear": 2012 }, { "name": "Alicia Keys", "age": 30, "hireYear": 2010 } ]

As shown in the output, the array is sorted by age ascending first, and for matching ages, by hireYear descending. This demonstrates a practical implementation of sorting an array by multiple fields using Lodash's _.orderBy method.

2024年6月29日 12:07 回复

你的答案