'Lodash orderBy on nested Arrays of objects
Have an array of objects with some nested properties:
const sports = [{
name: "Basketball",
leagues: [{
createdAt: 1
}, {
createdAt: 2
}]
},{
name: "Soccer",
leagues: [{
createdAt: 3
}, {
createdAt: 4
}]
}]
To get the array of object sorted by name DESC (Z->A) (non nested property) I do:
const sorted = _.orderBy(sports, item => item.name, ['desc']);
The result is
[{ name: "Soccer", ... },{ name: "Basketball", ... }]
What I am trying to achieve is to sort this object based on its nested array of objects leagues.createdAt DESC (assuming 1,2,3,4 are the correct timestamps):
[{
name: "Soccer",
leagues: [{
createdAt: 4
}, {
createdAt: 3
}]
},{
name: "Basketball",
leagues: [{
createdAt: 2
}, {
createdAt: 1
}]
}]
Tried to do smth like that:
const sorted = _.orderBy(sports, [(item) => item.leagues[0].createdAt], ["desc"])
but the order is not quite right:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|

