英文:
_lodash, sort by 2 fields(numbers, time)
问题
你可以使用lodash来按照timeFrom的hour和minute字段进行排序,如下所示:
_.sortBy(items, o => o.timeFrom.hour * 60 + o.timeFrom.minute);
这将会按照时间从早到晚的顺序对数组进行排序。
英文:
I have an array of object with data:
items = [
{
....someFields
timeFrom: {
hour: 17,
minute: 15
}
},
{
....someFields
timeFrom: {
hour: 12,
minute: 32
}
},
{
....someFields
timeFrom: {
hour: 17,
minute: 15
}
},
....someFields
timeFrom: {
hour: 17,
minute: 35
}
}
];
_.sortBy(items, o => o.timeFrom.hour);
How I can sort is by timeFrom hour and minute fields using lodash.
Thanks a lot.
答案1
得分: 3
Lodash支持一组_iteratees_来对每个元素进行运行。它还支持_.get()
的对象引用语法。
_.sortBy(items, ["timeFrom.hour", "timeFrom.minute"]);
当然,像这样的事情你几乎不需要整个第三方库。
// 规范化为分钟
[...items].sort(
(a, b) =>
(a.timeFrom.hour * 60 + a.timeFrom.minute) -
(b.timeFrom.hour * 60 + b.timeFrom.minute)
);
英文:
Lodash supports an array of iteratees to run each element through. It also supports the object reference syntax of _.get()
_.sortBy(items, ["timeFrom.hour", "timeFrom.minute"]);
Of course, you hardly need an entire 3rd party library for something like this
// normalise to minutes
[...items].sort(
(a, b) =>
(a.timeFrom.hour * 60 + a.timeFrom.minute) -
(b.timeFrom.hour * 60 + b.timeFrom.minute)
);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论