如何按日期对对象数组进行排序? [英] How to sort an array of objects by date?
本文介绍了如何按日期对对象数组进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试对一个对象数组进行排序,每个对象都包含:
I am trying to sort an array of objects with each object containing:
var recent = [{id: "123",age :12,start: "10/17/13 13:07"} , {id: "13",age :62,start: "07/30/13 16:30"}];
日期格式为:mm/dd/yy hh:mm
.
我想按日期顺序排序,最新的是第一个.如果日期相同,则应按其时间部分进行排序.
I want to sort in order of date with the most recent first. If date is same it should be sorted by their time parts.
我尝试了下面的sort()
函数,但是它不起作用:
I tried out the below sort()
function, but it is not working:
recent.sort(function(a,b))
{
a = new Date(a.start);
b = new Date(b.start);
return a-b;
});
我还应该如何遍历对象以进行排序?像这样:
Also how should I iterate over the objects for sorting? Something like:
for (var i = 0; i < recent.length; i++)
{
recent[i].start.sort(function (a, b)
{
a = new Date(a.start);
b = new Date(b.start);
return a-b;
} );
}
数组中可以有任意数量的对象.
There can be any number of objects in the array.
推荐答案
正如注释中指出的那样,recent的定义不是正确的javascript.
As has been pointed out in the comments, the definition of recent isn't correct javascript.
但是假设日期是字符串:
But assuming the dates are strings:
var recent = [
{id: 123,age :12,start: "10/17/13 13:07"},
{id: 13,age :62,start: "07/30/13 16:30"}
];
然后像这样排序:
recent.sort(function(a,b) {
return new Date(a.start).getTime() - new Date(b.start).getTime()
});
这篇关于如何按日期对对象数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文