gpt4 book ai didi

javascript - 按日期对嵌套的对象数组进行排序

转载 作者:搜寻专家 更新时间:2023-11-01 04:50:52 25 4
gpt4 key购买 nike

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

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 的嵌套数组中的对象已经按升序排序,但我还想根据分组的日期对数组本身进行排序。

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

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)},
]
]

用于排序的函数还应返回 dateGroups 的新排序版本。

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

最佳答案

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

_.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();
});

关于javascript - 按日期对嵌套的对象数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9293290/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com