gpt4 book ai didi

javascript - 按对象内的值和日期对数组进行排序

转载 作者:行者123 更新时间:2023-12-02 23:34:03 24 4
gpt4 key购买 nike

我有一个像这样的数组:

[{
Animal:{Tag:1, Eats:"Grass"},
Color:{Id:1, ColorName: "Black",
DateAndTime:"2019-06-06T13:45:00"
},
{
Animal:{Tag:2, Eats:"Meat"},
Color:{Id:2, ColorName: "Brown",
DateAndTime:"2019-06-07T13:45:00"
},
{
Animal:{Tag:3, Eats:"Water"},
Color:{Id:3, ColorName: "White",
DateAndTime:"2019-06-06T11:45:00"
},
{
Animal:{Tag:4, Eats:"Grass"},
Color:{Id:4, ColorName: "Yellow",
DateAndTime:"2019-06-06T14:45:00"
}]

我想以这样的方式排序:首先按“Eats”排序,然后在其中应按“DateAndTime”排序。所以,理想情况下它应该像这样返回:

[{
Animal:{Tag:1, Eats:"Grass"},
Color:{Id:1, ColorName: "Black",
DateAndTime:"2019-06-06T13:45:00"
}
,
{
Animal:{Tag:4, Eats:"Grass"},
Color:{Id:4, ColorName: "Yellow",
DateAndTime:"2019-06-06T14:45:00"
},
{
Animal:{Tag:3, Eats:"Meat"},
Color:{Id:3, ColorName: "White",
DateAndTime:"2019-06-06T11:45:00"
},
{
Animal:{Tag:2, Eats:"Meat"},
Color:{Id:2, ColorName: "Brown",
DateAndTime:"2019-06-07T13:45:00"
}]

使用lodash,我可以按日期和时间订购它,但我无法先按“Eats”订购它。任何帮助,将不胜感激。谢谢你!

最佳答案

您可以使用 string#localeCompare 首先在 Eats 字段上对数组进行排序,然后在 DateAndTime 字段上进行排序。

let data = [{ Animal:{Tag:1, Eats:"Grass"}, Color:{Id:1, ColorName: "Black"}, DateAndTime:"2019-06-06T13:45:00" }, { Animal:{Tag:2, Eats:"Meat"}, Color:{Id:2, ColorName: "Brown"}, DateAndTime:"2019-06-07T13:45:00" }, { Animal:{Tag:3, Eats:"Water"}, Color:{Id:3, ColorName:"White"}, DateAndTime:"2019-06-06T11:45:00" }, { Animal:{Tag:4, Eats:"Grass"}, Color:{Id:4, ColorName: "Yellow"}, DateAndTime:"2019-06-06T14:45:00" }];
data.sort((a,b) => a.Animal.Eats.localeCompare(b.Animal.Eats) || a.DateAndTime.localeCompare(b.DateAndTime));
console.log(data);
.as-console-wrapper {max-height: 100% !important; top: 0;}

您可以使用lodash#sortBy对数据进行排序。

let data = [{ Animal:{Tag:1, Eats:"Grass"}, Color:{Id:1, ColorName: "Black"}, DateAndTime:"2019-06-06T13:45:00" }, { Animal:{Tag:2, Eats:"Meat"}, Color:{Id:2, ColorName: "Brown"}, DateAndTime:"2019-06-07T13:45:00" }, { Animal:{Tag:3, Eats:"Water"}, Color:{Id:3, ColorName:"White"}, DateAndTime:"2019-06-06T11:45:00" }, { Animal:{Tag:4, Eats:"Grass"}, Color:{Id:4, ColorName: "Yellow"}, DateAndTime:"2019-06-06T14:45:00" }],
result = _.sortBy(data, ['Animal.Eats', 'DateAndTime']);
console.log(result);
.as-console-wrapper {max-height: 100% !important; top: 0;}
<script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.min.js"></script>

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

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