如何按日期排序对象的JavaScript数组 [英] How to sort a javascript 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 on time.
我尝试了下面的排序功能。但它不工作。
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 through 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.
推荐答案
正如已指出了意见,最近的定义是不正确的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"}
];
然后进行排序是这样的:
then sort like this:
recent.sort(function(a,b) {
return new Date(a.start).getTime() - new Date(b.start).getTime()
});
这篇关于如何按日期排序对象的JavaScript数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!