-1

i was working with some data that looks like this.

response={data:[{
    "time": "08:00",
    "date": "2022-06-30"
}, {
    "time": "16:30",
    "date": "2022-06-30",
}, {
    "time": "17:00",
    "date": "2022-06-27"
}, {
    "time": "11:00",
    "date": "2022-06-14"
}, {
    
    "time": "17:00",
    "date": "2022-06-14"
}, {
    "time": "08:30",
    "date": "2022-06-02"
}, {
    "time": "16:30",
    "date": "2022-06-02"
}, {
    "time": "16:30",
    "date": "2022-06-02"
}, {
    "time": "16:25",
    "date": "2022-06-02",
}]}

i wanted to sort this data by both of two fields (time & date).

  • by date, it should be in ascending order
  • by time, it should be in ascending order if dates are same in some items

requirement looks quite amazing. i searched on internet but can't get required results.

so i spent some time on it and made my own solution. so i am here to share this solution with stackoverflow-community.

here is my solution.

import moment from 'moment';
import { forEach, get, reverse } from 'lodash';
const data = get(response, 'data', []);
    //as data looks already in descending order by date
    reverse(data);
    //place datetime object in all items
    forEach(data, function(item) {
      item['datetime'] = moment(item.date + 'T' + item.time + ':' + '00');
    });
    //re-sort data by time in ascending order using datetime object
    data.sort(function(a, b) {
      return a.datetime - b.datetime;
    });

it is working finw but kindly let me know if we have any better sollution that should be efficient.

also let me know about your remarks for this solution.

Awais Kaleem
  • 11
  • 2
  • 9

1 Answers1

1

The task can also be done without lodash, simply by comparing date and time strings. The comparison of the dates happens first. If one is larger than the other then the second comparison of the times will not even happen, as the || (or) operator will only evaluate its second argument if the first argument was calculated as "falsy" (in our case 0).

const response={data:[{
"time": "08:00",
"date": "2022-06-30"
}, {
"time": "16:30",
"date": "2022-06-30"
}, {
"time": "17:00",
"date": "2022-06-27"
}, {
"time": "11:00",
"date": "2022-06-14"
}, {
"time": "17:00",
"date": "2022-06-14"
}, {
"time": "08:30",
"date": "2022-06-02"
}, {
"time": "16:30",
"date": "2022-06-02"
}, {
"time": "16:30",
"date": "2022-06-02"
}, {
"time": "16:25",
"date": "2022-06-02"
}]};

const res=response.data.slice(0).sort((a,b)=>
  a.date.localeCompare(b.date)||a.time.localeCompare(b.time));

console.log(res);
Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43