根据这些数据,我的排序函数将按日期、时间升序排序,并按名字的字母顺序排序:
[
['Kurt Asdf', '25 Nov 2017 4:30 PM'],
['Vincent Qwerty', '25 Nov 2017 4:30 PM'],
['Zed Jones', '24 Nov 2017 2:00 PM'],
['Jack Mo', '25 Nov 2017 5:00 PM'],
['John Phil', '25 Nov 2017 4:00 PM'],
['Bob Phil', '25 Nov 2017 4:00 PM']
]
这是我当前排序函数的输出(代码如下):
[
['Zed Jones', '24 Nov 2017 2:00 PM'],
['Bob Phil', '25 Nov 2017 4:00 PM'],
['John Phil', '25 Nov 2017 4:00 PM'],
['Kurt Asdf', '25 Nov 2017 4:30 PM'],
['Vincent Qwerty', '25 Nov 2017 4:30 PM'],
['Jack Mo', '25 Nov 2017 5:00 PM']
]
这是我想要的输出:
[
['Bob Phil', '25 Nov 2017 4:00 PM'],
['John Phil', '25 Nov 2017 4:00 PM'],
['Kurt Asdf', '25 Nov 2017 4:30 PM'],
['Vincent Qwerty', '25 Nov 2017 4:30 PM'],
['Jack Mo', '25 Nov 2017 5:00 PM'],
['Zed Jones', '24 Nov 2017 2:00 PM']
]
请注意,在上面的输出中,日期按降序排列,而时间按升序排列,并且每个时间段内的字母顺序保持不变。
这是我尝试过的:
function sortTable(data) {
return data.sort((elem1, elem2) => {
var dateA = new Date(elem1[1])
, dateB = new Date(elem2[1])
, nameA = elem1[0]
, nameB = elem2[0]
, datecomp = dateB-dateA;
if (nameA === undefined || nameB === undefined)
namecomp = 0;
else
namecomp = nameA[0] > nameB[0] || -(nameA[0] < nameB[0]);
return datecomp > 0 ? datecomp : datecomp + namecomp;
});
}
最佳答案
您可以使用链式方法以不同的排序顺序对部件进行排序。
我建议使用单个函数来比较和返回订单。
您可以使用ISO 8601用于按日期降序和时间升序排序的字符串。稍后按名称升序排序。
Why taking an ISO 8601 date/time string?
The conversion of
25 Nov 2017 4:30 PM
returns a sortable string in the format of
2017-11-25T15:30:00.000Z ISO in GMT ^^^^^^^^^^ date ^^^^^^^^ time without milli seconds
From this we take the date part for sorting descending
2017-11-25
and the time part
15:30:00
for sorting ascending, if the date is the same.
More to read here: Sort ISO 8601 dates forward or backwards.
var array = [['Kurt Asdf', '25 Nov 2017 4:30 PM'], ['Vincent Qwerty', '25 Nov 2017 4:30 PM'], ['Zed Jones', '24 Nov 2017 2:00 PM'], ['Jack Mo', '25 Nov 2017 5:00 PM'], ['John Phil', '25 Nov 2017 4:00 PM'], ['Bob Phil', '25 Nov 2017 4:00 PM']];
array.sort(function (a, b) {
function compare(a, b) {
return a > b || -(a < b);
}
var aISO = new Date(a[1]).toISOString(),
bISO = new Date(b[1]).toISOString();
return compare(bISO.slice(0, 10), aISO.slice(0, 10)) // date desc
|| compare(aISO.slice(11, 19), bISO.slice(11, 19)) // time asc
|| compare(a[0], b[0]); // name asc
});
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于JavaScript 排序函数,按日期降序和时间升序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47494026/