按两个属性对对象数组进行排序 [英] Sorting an Array of Objects by two Properties
问题描述
我有一个对象数组我要按两个属性排序:
I've got an Array of Objects I want to sort by two Properties:
- RemindingTimestamp
- ModificationTimestamp
排序顺序:desc
按此排序此对象一个属性不是问题,但在这种情况下我不知道如何让它工作。
Sorting this Object by one Property isn't the problem, but in this case I've no idea how to get it work.
推荐答案
假设时间戳本身排序好(例如ISO8601和同一时区),试试:
Presuming the timestamps themselves sort ok (e.g. ISO8601 and same time zone), try:
myArray.sort(function(a,b) {
var x = a.RemindingTimestamp - b.RemindingTimestamp;
return x == 0? a.ModificationTimestamp - b.ModificationTimestamp : x;
}
编辑 - 对评论的回应
通过改变减法的顺序来实现降序排序或者将结果乘以-1。由于它们没有减去而没有排序的日期(例如2012-04-12)可以通过首先转换为日期来处理,例如
Edit - response to comments
A descending sort is achieved by changing the order of subtraction, or multiplying the result by -1. Dates that don't sort because they don't subtract (e.g. 2012-04-12) can be handled by conversion to dates first, e.g.
// Convert ISO8601 date string to date object
// Assuming date is ISO8601 long format, ignores timezone
function toDate(s) {
var bits = s.split(/[-T :]/);
var d = new Date(bits[0], bits[1]-1, bits[2]);
d.setHours(bits[3], bits[4], parseFloat(bits[5]));
return d;
}
// Source data, should end up sorted per n
var myArray = [
{RemindingTimestamp: '2012-04-15T23:15:12Z',
ModificationTimestamp: '2012-04-15T23:15:12Z', n: 4},
{RemindingTimestamp: '2012-04-12T23:15:12Z',
ModificationTimestamp: '2012-04-12T23:15:12Z', n: 1},
{RemindingTimestamp: '2012-04-12T23:15:12Z',
ModificationTimestamp: '2012-04-13T23:15:12Z', n: 2},
{RemindingTimestamp: '2012-04-12T23:15:12Z',
ModificationTimestamp: '2012-04-13T23:15:14Z', n: 3}
];
// Sort it
myArray.sort(function(a,b) {
var x = toDate(a.RemindingTimestamp) - toDate(b.RemindingTimestamp);
return x? x : toDate(a.ModificationTimestamp) - toDate(b.ModificationTimestamp);
});
// Just to show the result
function sa(o) {
var result = [], t;
for (var i=0; i<o.length; i++) {
t = o[i];
result.push(t.n);
}
alert(result);
}
sa(myArray); // 1,2,3,4
日期字符串到日期对象的转换可以扩展为如果需要,处理时区(仅适用于符合ISO8601的字符串,使用时区缩写而不是实际偏移的字符串是不可靠的。)
The conversion of date string to date object can be extended to handle time zone if required (for ISO8601 compliant strings only, those that use time zone abbreviations instead of the actual offset are unreliable).
这篇关于按两个属性对对象数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!