Given the following data structure:
var MyData = [
{"id": 1, "status": "live", dateCreated: "12:00:00 01/02/2016"},
{"id": 2, "status": "draft", dateCreated: "13:00:00 03/12/2015"},
{"id": 3, "status": "ready", dateCreated: "16:00:00 04/09/2016"},
{"id": 4, "status": "ready", dateCreated: "10:00:00 01/10/2016"},
{"id": 5, "status": "live", dateCreated: "09:00:00 05/07/2015"},
{"id": 6, "status": "draft", dateCreated: "08:00:00 11/03/2016"},
{"id": 7, "status": "ready", dateCreated: "20:00:00 12/02/2016"}
]
I'm trying to sort and group it into these conditions:
- Grouped by status
- Ordered by status such that the order is "live", "draft", "ready"
- Items within each status should be ordered by dateCreated, most recent first.
What I have so far:
// this object will help us define our custom order as it's not alphabetical
const itemOrder = {
'live': 1,
'ready': 2,
'draft': 3
};
const sortByStatus = (statusA, statusB) => {
if ( itemOrder[statusA] > itemOrder[statusB] ) return 1;
if ( itemOrder[statusA] < itemOrder[statusB] ) return -1;
return 0;
};
return List(MyData)
.groupBy(item => item.status)
.sort( sortByStatus )
Ignore for a moment the fact that I've not got to the point where I can sort by date yet :)
The problem with the above seems to be that sortByStatus is being passed the IndexedIterable that is the overall group but not it's key so I can't sort it by that key. I think I probably need to use sortBy but the Immutable.js docs are incomprehensible and have no examples on which to work out how to achieve this.
So, the question: how can I take the result of the groupBy action and sort it into a custom order and additionally how can I ensure that all the items in each group are sorted by date?