Reputation: 359
I need to use lodash to implement a custom sort based on classification, then by creation time, with more recently created items with the same classification having a lower index in the array. I'm pretty sure I need to use orderBy
, but I don't know how to add the date sorting part. This is what I have:
let sorted = _.orderBy(this.followed_requests, function(element){
const rank = { "INCOMPLETE.NEW": 1,
"INCOMPLETE.IN_PROGRESS":2,
"INCOMPLETE.LATER":3}
return rank[element["status"]]})
I'd like my output to have something like:
sorted = [{status:"INCOMPLETE.NEW", created_at: "2021-05-14T14:48:00.000Z"},
{status:"INCOMPLETE.NEW", created_at: "2021-05-13T14:48:00.000Z"},
{status:"INCOMPLETE.IN_PROGRESS", created_at: "2021-05-14T14:48:00.000Z"},
{status:"INCOMPLETE.IN_PROGRESS", created_at: "2021-05-13T14:48:00.000Z"},
{status:"INCOMPLETE.LATER", created_at: "2021-05-14T14:48:00.000Z"},
{status:"INCOMPLETE.NEW", created_at: "2021-05-13T14:48:00.000Z"} ]
Upvotes: 0
Views: 978
Reputation: 160251
orderBy
accepts an array of functions and sort directions. There's multiple ways this could be implemented, but since both sort values require transformation this seems like a good option.
const reqs = [
{ status: "INCOMPLETE.LATER", created_at: "2021-05-14T14:48:00.000Z" },
{ status: "INCOMPLETE.NEW", created_at: "2021-05-13T15:48:00.000Z" },
{ status: "INCOMPLETE.IN_PROGRESS", created_at: "2021-05-14T14:48:00.000Z" },
{ status: "INCOMPLETE.IN_PROGRESS", created_at: "2021-05-13T15:48:00.000Z" },
{ status: "INCOMPLETE.NEW", created_at: "2021-05-14T16:48:00.000Z" },
{ status: "INCOMPLETE.NEW", created_at: "2021-05-13T14:48:00.000Z" },
]
const rank = {
"INCOMPLETE.NEW": 1,
"INCOMPLETE.IN_PROGRESS": 2,
"INCOMPLETE.LATER": 3,
}
let sorted = _.orderBy(reqs, [
i => rank[i.status],
i => new Date(i.created_at)
], ["asc", "asc"])
console.log(sorted)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
Upvotes: 2