如何按日期排序对象的JavaScript数组 [英] How to sort a javascript array of objects by date

查看:140
本文介绍了如何按日期排序对象的JavaScript数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图排序一个对象数组,每个对象包含

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.

但假设日期是字符串:

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() 
});

有关W3Schools的排序功能的详细信息

这篇关于如何按日期排序对象的JavaScript数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆