简体   繁体   English

如何按日期范围和创建日期对对象数组进行排序?

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

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: 使用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? 但是,当我仍然尝试根据创建日期对它们进行基本排序时,如何考虑上下文的​​开始日期和结束日期呢?

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: 阅读http://underscorejs.org/提供的doco表示,它是一种稳定的排序算法(这意味着如果值相等,它不会抛出多个排序的顺序。请参阅http://en.wikipedia .org / wiki / Sorting_algorithm ),因此您应该能够安全地链接排序上下文:

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? 您是否尝试过并且可以提供一些样本数据进行测试?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM