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

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

问题描述

这是我的阵列

arr=[
{
    date:'2017-06-14 14:03:49'
},
{
    date:'2017-04-20 10:25:32'
},
{
    date:'2017-06-02 15:57:16'
},
{
    date:'2017-06-02 17:52:05'
},
{
    date:'2017-06-02 21:47:13'
},
{
    date:'2017-06-14 14:01:31'
}
]

我需要按日期对数组进行排序.

I need sort an array by date.

我该怎么做

请劝我

谢谢

推荐答案

使用 Array#sort 方法和compare函数中的函数,通过获取差值来解析字符串并返回相应的值.

Use Array#sort method and within compare function parse the string and return value corresponding by getting the difference.

var arr = [{
  date: '2017-06-14 14:03:49'
}, {
  date: '2017-04-20 10:25:32'
}, {
  date: '2017-06-02 15:57:16'
}, {
  date: '2017-06-02 17:52:05'
}, {
  date: '2017-06-02 21:47:13'
}, {
  date: '2017-06-14 14:01:31'
}];

arr.sort(function(a, b) {
  // convert date object into number to resolve issue in typescript
  return  +new Date(a.date) - +new Date(b.date);
})

console.log(arr);

请参考git中的问题:对日期进行算术运算时出错

Refer the issue in git: Error when doing arithmetic operations on date

或参考: TypeScript按日期排序不起作用

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

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