假设我有一个看起来像这样的数组
[ [AAAA, 2016-01-01, 1:00 PM, FA1],
[AAAA, 2016-01-01, 12:30 AM, FA1],
[BBBB, 2016-01-02, 6:00 PM, FA1],
[BBBB, 2016-01-02, 5:00 PM, FA1],
[CCCC, 2016-01-03, 9:00 PM, FA1],
[CCCC, 2016-01-03, 7:00 PM, FA1] ]
如何对数据进行排序,看起来像这样。
[ [AAAA, 2016-01-01, 12:30 AM, FA1],
[AAAA, 2016-01-01, 1:30 PM, FA1],
[BBBB, 2016-01-02, 5:00 PM, FA1],
[BBBB, 2016-01-02, 6:00 PM, FA1],
[CCCC, 2016-01-03, 7:00 PM, FA1],
[CCCC, 2016-01-03, 9:00 PM, FA1] ]
现在这是我的代码,但它不按时间排序
var inputarr = [
["AAAA", "2016-01-01, 1:00 PM", "FA1"],
["AAAA", "2016-01-01, 12:30 AM", "FA1"],
["BBBB", "2016-01-02, 6:00 PM", "FA1"],
["BBBB", "2016-01-02, 5:00 PM", "FA1"],
["CCCC", "2016-01-03, 9:00 PM", "FA1"],
["CCCC", "2016-01-03, 7:00 PM", "FA1"]
]
map = {};
for (var element in inputarr) {
if (!map[inputarr[element][1]]) {
map[inputarr[element][1]] = [];
}
map[inputarr[element][1]].push(inputarr[element]);
}
output = [];
for (var key in map) {
output.push(map[key].shift());
output.push(map[key].pop());
}
console.log(output);
答案 0 :(得分:3)
您可以使用Date
对象对字段进行排序,使用字符串方法localCompare
对字符串进行排序。
x = [
['AAAA', '2016-01-01', '1:00 PM', 'FA1'],
['AAAA', '2016-01-01', '12:30 AM', 'FA1'],
['BBBB', '2016-01-02', '6:00 PM', 'FA1'],
['BBBB', '2016-01-02', '5:00 PM', 'FA1'],
['CCCC', '2016-01-03', '9:00 PM', 'FA1'],
['CCCC', '2016-01-03', '7:00 PM', 'FA1']
]
x.sort((a, b) => {
let aDate = new Date(`${a[1]} ${a[2]}`),
bDate = new Date(`${b[1]} ${b[2]}`);
if (+aDate == +bDate) {
return a[0].localeCompare(b[0])
}
return aDate - bDate;
})
console.log(x)