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:
javascriptconst _ = require('lodash');
Then, assume the following array:
javascriptlet 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:
javascriptlet 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:
javascriptconsole.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.