_lodash, sort by 2 fields(numbers, time)

54 Views Asked by At

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

There are 1 best solutions below

2
Phil On BEST ANSWER

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