在Javascript中按时间排序日期列表

时间:2018-05-04 21:07:22

标签: javascript arrays sorting date

我有一个像这样的数组对象:

[
 {
  _id: 1
  date: '2018-05-04T12:28:00-07:00' //12:28pm
 },
 {
  _id: 2
  date: '2018-04-29T08:24:00-07:00' //8:24am
 },
 {
  _id: 3
  date: '2018-05-04T10:29:00-07:00' //10:29am
 }

现在,我想通过" TIME"对这个数组进行排序。只是不管日期

排序数组应如下所示:

[
 {
  _id: 2
  date: '2018-04-29T08:24:00-07:00' //8:24am
 },
 {
  _id: 3
  date: '2018-05-04T10:29:00-07:00' //10:29am
 },
 {
  _id: 1
  date: '2018-05-04T12:28:00-07:00' //12:28pm
 }
]

如何在Javascript中编写此代码?

我试过了:

sorted.sort((a, b) => {
  return new Date(a.start_ts).getUTCHours() - new Date(b.start_ts).getUTCHours()
})

但似乎给我一个错误,"不能在不可变数据结构上调用sort方法。"

3 个答案:

答案 0 :(得分:1)

您的代码无法正常工作,因为正在排序的对象没有 start_ts 属性。如果您发布有效的JavaScript,它也会有所帮助。

考虑到时间组件的格式,可以使用 date 属性和 localeCompare 将对象排序为字符串:

var data = [
   {_id: 1, date: '2018-05-04T12:28:00-07:00'},
   {_id: 2, date: '2018-04-29T08:24:00-07:00'},
   {_id: 3, date: '2018-05-04T10:29:00-07:00'}
];

data.sort((a, b) => a.date.substr(11,8).localeCompare(b.date.substr(11,8)));

console.log(data);

答案 1 :(得分:0)

无需弄乱日期,只需提取每个字符串的小时/分钟/秒并进行相应排序:



const arr = [{
    _id: 1,
    date: '2018-05-04T12:28:00-07:00' //12:28pm
  },
  {
    _id: 2,
    date: '2018-04-29T08:24:00-07:00' //8:24am
  },
  {
    _id: 3,
    date: '2018-05-04T10:29:00-07:00' //10:29am
  }
];
const hmsVal = str => {
  const [,h, m, s] = str.match(/(\d\d):(\d\d):(\d\d)/);
  return Number(h) * 3600 + Number(m) * 60 + Number(s);
};
arr.sort((a, b) => hmsVal(a.date) - hmsVal(b.date));
console.log(arr);




答案 2 :(得分:0)

考虑对此数组进行排序" TIME"只要不考虑日期



const input = [{
    _id: 1,
    date: "2018-05-04T12:28:00-07:00"
  },
  {
    _id: 2,
    date: "2018-04-29T08:24:00-07:00"
  },
  {
    _id: 3,
    date: "2018-05-04T10:29:00-07:00"
  }
];
input.sort((a,b) => {
  return getDate(a) - getDate(b)
});

function getDate(i) {
  let temp = new Date(i.date);
  let currentDate = new Date();
  temp.setUTCFullYear(currentDate.getUTCFullYear(),
    currentDate.getUTCMonth(),
    currentDate.getUTCDate());
  return temp;
}
console.log(input);




setUTCFullYear()