_lodash,按照2个字段排序(数字,时间)

huangapple go评论94阅读模式
英文:

_lodash, sort by 2 fields(numbers, time)

问题

你可以使用lodash来按照timeFromhourminute字段进行排序,如下所示:

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

huangapple
  • 本文由 发表于 2023年6月29日 11:56:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/76577971.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定