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

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

_lodash, sort by 2 fields(numbers, time)

问题

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

  1. _.sortBy(items, o => o.timeFrom.hour * 60 + o.timeFrom.minute);

这将会按照时间从早到晚的顺序对数组进行排序。

英文:

I have an array of object with data:

  1. items = [
  2. {
  3. ....someFields
  4. timeFrom: {
  5. hour: 17,
  6. minute: 15
  7. }
  8. },
  9. {
  10. ....someFields
  11. timeFrom: {
  12. hour: 12,
  13. minute: 32
  14. }
  15. },
  16. {
  17. ....someFields
  18. timeFrom: {
  19. hour: 17,
  20. minute: 15
  21. }
  22. },
  23. ....someFields
  24. timeFrom: {
  25. hour: 17,
  26. minute: 35
  27. }
  28. }
  29. ];
  30. _.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()的对象引用语法。

  1. _.sortBy(items, ["timeFrom.hour", "timeFrom.minute"]);

当然,像这样的事情你几乎不需要整个第三方库。

  1. // 规范化为分钟
  2. [...items].sort(
  3. (a, b) =>
  4. (a.timeFrom.hour * 60 + a.timeFrom.minute) -
  5. (b.timeFrom.hour * 60 + b.timeFrom.minute)
  6. );
英文:

Lodash supports an array of iteratees to run each element through. It also supports the object reference syntax of _.get()

  1. _.sortBy(items, ["timeFrom.hour", "timeFrom.minute"]);

Of course, you hardly need an entire 3rd party library for something like this

  1. // normalise to minutes
  2. [...items].sort(
  3. (a, b) =>
  4. (a.timeFrom.hour * 60 + a.timeFrom.minute) -
  5. (b.timeFrom.hour * 60 + b.timeFrom.minute)
  6. );

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:

确定