How to sort an array of objects by date range and creation date?

1.6k views Asked by At

I'm building a task list system, but for the life of me I can't figure out a way to sort an array of objects with a start and end date.

I want to default the task list by the task's creation date, and work on oldest tasks first.

I dont want to start a task until it is at least on the start date.

I want to complete a task a day before the end date.

Sorting the dates by start date is easy using underscorejs:

_.sortBy(arr, function(task) { 
    return task.start.dateTime; 
})

But how do I take into context start date and end date, while still trying to keep it basely sorted by creation date?

1

There are 1 answers

0
rurouni88 On

Reading the doco provided by http://underscorejs.org/ sortBy says that it is a stable sort algorithm (meaning that it won't throw out the order on multiple sorts if the values are equal. See http://en.wikipedia.org/wiki/Sorting_algorithm) so you should be able to chain up sorting context safely:

var sortedArray = _(arr).chain()
.sortBy(function(task) {
    return task.created.dateTime;
})
.sortBy(function(task) {
    return task.start.dateTime;
})
.sortBy(function(task) {
    return task.end.dateTime;
})
.value();

Have you tried that and can you provide some sample data to test with?