Sorting Arrays With Lodash's sortBy() Function
JavaScript has a built-in Array#sort()
function that sorts an array in place.
The built-in sort()
function works well, but can get cumbersome when sorting
arrays of objects.
On the other hand, _.sortBy()
lets you
sort an array of objects by a property name as shown below.
const characters = [
{ name: 'Jean-Luc Picard', age: 59 },
{ name: 'William Riker', age: 29 },
{ name: 'Deanna Troi', age: 28 },
{ name: 'Worf', age: 24 }
];
// Sort characters by the `age` property
const sorted = _.sortBy(characters, 'age');
sorted[0].name; // Worf
sorted[1].name; // Deanna Troi
sorted[2].name; // William Riker
sorted[3].name; // Jean-Luc Picard
The first parameter to sortBy()
is the array to sort, and then 2nd parameter
is called the iteratees
. You can think of iteratees
as a function that
transforms each array element into something that is sortable. For example,
instead of passing the property name age
as a string, you can instead pass
an iteratees
function as the 2nd parameter.
const characters = [
{ name: 'Jean-Luc Picard', age: 59 },
{ name: 'William Riker', age: 29 },
{ name: 'Deanna Troi', age: 28 },
{ name: 'Worf', age: 24 }
];
// Sort characters by the `age` property
const iteratees = obj => obj.age;
const sorted = _.sortBy(characters, iteratees);
sorted[0].name; // Worf
sorted[1].name; // Deanna Troi
sorted[2].name; // William Riker
sorted[3].name; // Jean-Luc Picard
There are numerous other ways to use iteratees
to transform the array.
For example, instead of sorting by the character's age, you can sort by the
length of the character's name.
const characters = [
{ name: 'Jean-Luc Picard', age: 59 },
{ name: 'William Riker', age: 29 },
{ name: 'Deanna Troi', age: 28 },
{ name: 'Worf', age: 24 }
];
// Sort characters by the length of their name, longest first. Note
// the negative sign.
const iteratees = obj => -obj.name.length;
const sorted = _.sortBy(characters, iteratees);
sorted[0].name; // Jean-Luc Picard
sorted[1].name; // William Riker
sorted[2].name; // Deanna Troi
sorted[3].name; // Worf