按日期对嵌套的对象数组进行排序 [英] Sorting nested arrays of objects by date

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

问题描述

我正在尝试对如下所示的数组进行排序:

I'm trying to sort an array that looks like this:

var dateGroups = [
  [
     {age:20, date: Fri Feb 03 2012 14:30:00 GMT+1100 (EST)}, 
     {age:12, date: Fri Feb 03 2012 18:20:00 GMT+1100 (EST)}, 
     {age:18, date: Fri Feb 03 2012 21:43:00 GMT+1100 (EST)}
  ],
  [
     {age:32, date: Fri Feb 01 2012 10:54:00 GMT+1100 (EST)}, 
     {age:44, date: Fri Feb 01 2012 11:45:00 GMT+1100 (EST)}, 
  ],
  [
     {age:22, date: Fri Feb 05 2012 10:54:00 GMT+1100 (EST)}, 
     {age:22, date: Fri Feb 05 2012 18:22:00 GMT+1100 (EST)},
  ]
]

dateGroups 的嵌套数组中的对象已经按升序排序,但我还想根据分组日期对数组本身进行排序.

The objects inside dateGroups' nested arrays are already sorted in ascending order, but I also want to sort the arrays themselves based on the grouped dates.

在这种情况下,数组应如下所示:

In this case the array should then look like this:

var dateGroups = [
  [
     {age:32, date: Fri Feb 01 2012 10:54:00 GMT+1100 (EST)}, 
     {age:44, date: Fri Feb 01 2012 11:45:00 GMT+1100 (EST)}, 
  ],
  [
     {age:20, date: Fri Feb 03 2012 14:30:00 GMT+1100 (EST)}, 
     {age:12, date: Fri Feb 03 2012 18:20:00 GMT+1100 (EST)}, 
     {age:18, date: Fri Feb 03 2012 21:43:00 GMT+1100 (EST)}
  ],
  [
     {age:22, date: Fri Feb 05 2012 10:54:00 GMT+1100 (EST)}, 
     {age:22, date: Fri Feb 05 2012 18:22:00 GMT+1100 (EST)},
  ]
]

用于排序的函数还应返回日期组的新排序版本.

The function used to sort should also return the new sorted version of dateGroups.

我试过使用 Underscore.js 的 sortBy() 函数,但我不知道如何根据其中一个对象内的属性值对数组进行排序.有没有一种特定的方式来对 Date 对象进行排序?或者它们的排序方式与数字或字母相同?

I've tried using Underscore.js's sortBy() function but I can't figure out how to sort the arrays based on the value of a property inside one of the objects. Is there a specific way to sort Date objects? Or are they sorted in the same way as numbers or letters?

推荐答案

根据 Underscore.js 文档,您应该为此原因编写自己的迭代器.像这样:

According to Underscore.js documentation, you should simply write your own iterator for that cause. Something like this:

_.sortBy(dateGroups, function(arrayElement) {
    //element will be each array, so we just return a date from first element in it
    return arrayElement[0].date.getTime();
});

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

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