按对象和日期中的值对数组进行排序

时间:2019-05-29 11:48:21

标签: javascript arrays sorting ecmascript-6 lodash

我有一个像这样的数组:

[{
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,我可以通过DateAndTime对其进行排序,但无法首先通过“ Eats”对其进行排序。任何帮助,将不胜感激。谢谢!

2 个答案:

答案 0 :(得分:1)

您可以使用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>

答案 1 :(得分:0)

使用lodash,您可以在数组中传递要排序的属性:

const results = _.sortBy(data, ['Animal.Eats', 'DateAndTime']);

这将对每个属性按升序对数组进行排序。如果要更改顺序,请使用orderBy函数:

const results = _.orderBy(data, ['Animal.Eats', 'DateAndTime'], ['asc', 'desc']);