我想使用js对对象数组进行排序。这是我实施的内容。
var employees = []
employees[0] = {
retiredate: "01/12/2014"
}
employees[1] = {
retiredate: "29/01/2015"
}
employees[2] = {
retiredate: "05/12/2014"
}
employees[3] = {
retiredate: "08/12/2014"
}
employees[4] = {
retiredate: "11/12/2014"
}
employees[5] = {
retiredate: "14/01/2015"
}
employees[6] = {
retiredate: "03/12/2014"
}
employees[7] = {
retiredate: "16/01/2015"
}
employees[8] = {
retiredate: "19/01/2015"
}
employees[9] = {
retiredate: "22/01/2015"
}
employees[10] = {
retiredate: "28/01/2015"
}
employees[11] = {
retiredate: "23/01/2015"
}
employees[12] = {
retiredate: "15/01/2015"
}
//console.log(periodesSorted);
console.log("START ... ")
employees.sort(function(a, b) {
var dateA = new Date(a.retiredate),
dateB = new Date(b.retiredate)
return dateA - dateB //sort by date ascending
})
for (ind2 = 0; ind2 < employees.length; ind2++) {
console.log(employees[ind2].retiredate)
}
console.log("End ... ")
在firefox中,retiredate数组排序很好。
在chrome中,我有以下结果
01/12/2014
15/01/2015
05/12/2014
08/12/2014
11/12/2014
14/01/2015
29/01/2015
16/01/2015
19/01/2015
22/01/2015
28/01/2015
23/01/2015
03/12/2014
结果未排序。我在哪里出错了? 有人可以建议修复此问题吗?
此致
答案 0 :(得分:1)
而不是:
new Date(a.retiredate)
在创建日期之前,将dd / mm / yyyy转换为yyyy-mm-dd:
new Date(a.retiredate.replace( /(\d{2})\/(\d{2})\/(\d{4})/, "$3-$2-$1") );
工作JSFiddle: http://jsfiddle.net/inanda/csz56b0q/1/
答案 1 :(得分:1)
在我们的情况下,您需要将日期转换为mm/dd/yyyy
格式,您可以这样做
employees.sort(function(a, b) {
var toDate = function (date) {
var res = date.split('/');
return new Date(res[2], res[1], res[0]).getTime();
// getTime returns the number of milliseconds
// or you can use + before new Date..
};
return toDate(a.retiredate) - toDate(b.retiredate);
})
答案 2 :(得分:1)
您可以使用
employees.sort(function (d1, d2) {
function parseDate(str) {
var parts = str.match(/(\d+)/g);
// assumes M/D/Y date format
return new Date(parts[2], parts[0]-1, parts[1]); // months are 0-based
}
return parseDate(d1.retiredate) - parseDate(d2.retiredate);
});
这是示例Link
答案 3 :(得分:0)
就我个人而言,我会避免所有重新解析&amp;日期构建(样本中84次);
// prepare the data by appending a date from a reformatted string
for (var i = 0; i < employees.length; i++) {
var dateString = employees[i].retiredate;
employees[i]._date = new Date(dateString.substr(6, 4) + "-" + dateString.substr(3, 2) + "-" + dateString.substr(0, 2));
}
// sort without conversion
employees.sort(function(a, b) {
return a._date - b._date;
})