我对编程并不陌生,无法理解为什么我的排序功能无法按日期排序?
var customer_orders = [
{
order_number: 1,
customer: 'Jess Learmonth',
total_cost: 200,
processed_date: '23/01/2016'
},
{
order_number: 14,
customer: 'Adam Bowden',
total_cost: 100,
processed_date: '22/01/2015'
}
];
customer_orders.sort(function(a, b) {
var dateA = new Date(a.processed_date), dateB = new Date(b.processed_date);
return dateA - dateB;
});
答案 0 :(得分:0)
由于未对您的日期格式进行检查,因此未排序。您可以尝试以下操作:
var customer_orders = [{order_number:1,customer:'Jess Learmonth',total_cost:200,processed_date:'23/01/2016'},{order_number:14,customer:'Adam Bowden',total_cost:100,processed_date:'22/01/2015'}];
customer_orders.sort((a,b)=> a.processed_date.split('/').reverse().join('').localeCompare(b.processed_date.split('/').reverse().join('')));
console.log(customer_orders);
答案 1 :(得分:0)
由于您的日期格式不是按日期识别的日期格式,因此可以像这样进行转换
var customer_orders = [{
order_number: 1,
customer: 'Jess Learmonth',
total_cost: 200,
processed_date: '23/01/2016'
},
{
order_number: 14,
customer: 'Adam Bowden',
total_cost: 100,
processed_date: '22/01/2015'
}
];
function reformatDate(dateString) {
var dateParts = dateString.split("/");
return new Date(dateParts[2], dateParts[1] - 1, dateParts[0]);
}
customer_orders.sort(function(a, b) {
return new Date(reformatDate(a.processed_date)) - new Date(reformatDate(b.processed_date));
});
console.log(customer_orders);
答案 2 :(得分:0)
您应该使用momentjs
来解析日期,并比较它们以进行排序-
var customer_orders = [{
order_number: 1,
customer: 'Jess Learmonth',
total_cost: 200,
processed_date: '23/01/2016'
},
{
order_number: 14,
customer: 'Adam Bowden',
total_cost: 100,
processed_date: '22/01/2015'
}
];
let ans = customer_orders.sort(function(a, b) {
var dateA = moment(a.processed_date, "DD/MM/YYYY"),
dateB = moment(b.processed_date, "DD/MM/YYYY");
return dateA - dateB;
});
console.log(ans);
<script src="https://momentjs.com/downloads/moment.min.js"></script>