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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19430561/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 15:34:24  来源:igfitidea点击:

How to sort an array of objects by date?

javascriptarrayssortingdate

提问by Anthea

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.

数组中可以有任意数量的对象。

回答by Chris Charles

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 有关排序功能的更多详细信息

回答by Tom Bowers

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

回答by cchamberlain

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)

回答by stayingcool

ES6:

ES6:

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