[英]Sort array of objects following multiple rules in javascript
So I have an array of objects, and I would like to sort them following these two rules (in order of priority): 所以我有一个对象数组,我想按照以下两个规则对它们进行排序(按优先级顺序):
So, I want the objects not only to be sorted by numbers, but to be also be sorted by time. 因此,我希望对象不仅要按数字排序,而且还要按时间排序。 For example, this would be ok. 例如,这可以。
This is the structure of the part of the objects that interests us: 这是我们感兴趣的对象部分的结构:
var notSortedData = {
number: number, // it's a string
scheduled_date: scheduled_date, // the format is "YYYY-MM-DD HH:MM:SS"
}
sortedTrains.push(notSortedData);
So, notSortedData
is pushed in sortedTrains
via a for
loop. 因此, notSortedData
通过for
循环被推入sortedTrains
。 Then I do this, but it is not enough (as it doesn't respect my second condition): 然后我这样做,但这还不够(因为它不符合我的第二个条件):
// sorts all the numbers numerically
sortedTrains.sort(function(a, b) {
return parseInt(a.number) - parseInt(b.number);
});
What do I need to do to make sure that my second condition is also respected? 我该怎么做才能确保我的第二个条件也得到尊重? Thanks! 谢谢!
You can try this: 您可以尝试以下方法:
sortedTrains.sort(function(a, b) {
// We parse the numbers
var num1 = parseInt(a.number), num2 = parseInt(b.number);
if (num1 != num2) return num1 - num2; // Return the difference IF they are not equal
var date1 = new Date(a.scheduled_date), date2 = new Date(b.scheduled_date);
// We only get here if the numbers are equal
return date1 - date2;
});
I would suggest to utilize a library such as underscore or lo-Dash, because later you might add more sort conditions or change them and using the library will greatly reduce the noisiness of your code and save you development effort. 我建议使用下划线或lo-Dash之类的库,因为以后您可能会添加更多排序条件或更改它们,并且使用该库将大大减少代码的繁琐并节省开发工作。 Assuming lo-Dash is used, the code will be as elegant as follows: 假设使用lo-Dash,代码将如下所示:
var sortedTrains = [
{ 'number': 5, 'scheduled_date': '2014-10-12 00:00:00'},
{ 'number': 5, 'scheduled_date': '2014-10-12 01:00:00' },
{ 'number': 5, 'scheduled_date': '2014-10-12 02:00:00'},
{ 'number': 6, 'scheduled_date': '2014-10-12 03:00:00' }
];
var result = _.sortBy(sortedTrains, ['number', 'scheduled_date']);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.