简体   繁体   English

如何按日期对对象数组进行排序?

[英]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"}];

Date format is: mm/dd/yy hh:mm . 日期格式为: 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. 如果日期相同,则应按时间部分排序。

I tried out the below sort() function, but it is not working: 我尝试了下面的sort()函数,但它不起作用:

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. 数组中可以有任意数量的对象。

As has been pointed out in the comments, the definition of recent isn't correct javascript. 正如在评论中指出的那样,最近的定义是不正确的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() 
});

More details on sort function from W3Schools 有关W3Schools排序功能的更多细节

recent.sort(function(a,b) { return new Date(a.start).getTime() - new Date(b.start).getTime() } );

This function allows you to create a comparator that will walk a path to the key you would like to compare on: 此功能允许您创建一个比较器,该比较器将路径指向您要比较的键:

 function createDateComparator ( path = [] , comparator = (a, b) => a.getTime() - b.getTime()) { return (a, b) => { let _a = a let _b = b for(let key of path) { _a = _a[key] _b = _b[key] } return comparator(_a, _b) } } const input = ( [ { foo: new Date(2017, 0, 1) } , { foo: new Date(2018, 0, 1) } , { foo: new Date(2016, 0, 1) } ] ) const result = input.sort(createDateComparator([ 'foo' ])) console.info(result) 

ES6:

recent.sort((a,b)=> new Date(b.start).getTime()-new Date(a.start).getTime());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM