按日期对具有日期字段的对象数组进行排序 [英] Sort array of objects with date field by date

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

问题描述

给出以下对象数组,我需要按日期字段升序对它们进行排序。

Give the following array of objects, I need to sort them by the date field ascending.

var myArray = [
  {
    name: "Joe Blow",
    date: "Mon Oct 31 2016 00:00:00 GMT-0700 (PDT)"
  },
  {
    name: "Sam Snead",
    date: "Sun Oct 30 2016 00:00:00 GMT-0700 (PDT)"
  },
  {
    name: "John Smith",
    date: "Sat Oct 29 2016 00:00:00 GMT-0700 (PDT)"  
  }
];

因此在本例中,最终结果将是John Smith,Sam Snead和Joe Blow。

so that in this example, the final result would be John Smith, Sam Snead, and Joe Blow.

我正在尝试使用lodash的 _。 sortBy(),但无论我如何使用它,我都无法进行任何排序:

I am trying to use lodash's _.sortBy(), but I can't get any sorting to take place no matter how I try to use it:

_.sortBy(myArray, function(dateObj) {
  return dateObj.date;
});

_.sortBy(myArray, 'date');

我需要更改什么来正确排序我的数组?我也有Moment.js,所以我可以根据需要使用它来格式化日期字符串。我尝试使用.unix()转换日期属性,但这没有什么区别。

What do I need to change to get my array sorted properly? I also have Moment.js, so I can use it to format the date string if needed. I tried converting the date property using .unix(), but that didn't make a difference.

谢谢。

推荐答案

你真的不需要lodash。只需使用JavaScript的 Array.prototype.sort 方法。

You don't really need lodash. Just use JavaScript's Array.prototype.sort method.

您需要创建日期日期字符串中的对象,然后才能比较它们。

You'll need to create Date objects from your date strings before you can compare them.

var myArray = [{
  name: "Joe Blow",
  date: "Mon Oct 31 2016 00:00:00 GMT-0700 (PDT)"
}, {
  name: "Sam Snead",
  date: "Sun Oct 30 2016 00:00:00 GMT-0700 (PDT)"
}, {
  name: "John Smith",
  date: "Sat Oct 29 2016 00:00:00 GMT-0700 (PDT)"
}];

myArray.sort(function compare(a, b) {
  var dateA = new Date(a.date);
  var dateB = new Date(b.date);
  return dateA - dateB;
});

console.log(myArray);

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

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