如何按日期对对象数组进行排序? [英] How to sort an array of objects by date?

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

问题描述

我正在尝试对一个对象数组进行排序,每个对象包含:

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.

推荐答案

正如评论中所指出的,最近的 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 排序功能的细节

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

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