Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort according to time in array of Object?

I have an array of object such as

[{
  time: "13:20",
  key2: "",
  key3: ""
}, {
  time: "13:40",
  key2: "",
  key3: ""
}, {
  time: "04:20",
  key2: "",
  key3: ""
}]

and I want them to sort according to time. I did some research on momentjs but I didn't found something useful.

The main problem I am facing is How to convert that time that I am getting into String format to some comparable format for sorting. Any kind of help will be appreciated.Thank you.

like image 309
Tanvir Singh Avatar asked Dec 22 '22 23:12

Tanvir Singh


2 Answers

You make a same date for all the times. And then getTime() and compare that

let arr = [{
  time: "13:20",
  key2: "",
  key3: ""
}, {
  time: "13:40",
  key2: "",
  key3: ""
}, {
  time: "04:20",
  key2: "",
  key3: ""
}]

const toTime = (t) => new Date(`December 17, 1995 ${t}`).getTime();


arr.sort((a,b) => toTime(a.time) - toTime(b.time))

console.log(arr)
like image 146
Maheer Ali Avatar answered Dec 25 '22 22:12

Maheer Ali


You can take following approach to sort it:

Logic

  • Create date object and add necessary time value you have.
  • Sort it based on these date values.

Benefit of having date based approach is that it will handle all time value cases. I have updated data to have second values as well for demonstration

var data = [{
  time: "13:20",
  key2: "",
  key3: ""
}, {
  time: "13:40",
  key2: "",
  key3: ""
}, {
  time: "04:20:10",
  key2: "",
  key3: ""
}, {
  time: "04:20:20",
  key2: "",
  key3: ""
}];

function getAddedTimeValue(time) {
  const parts = [...time.split(':'), 0, 0, 0, 0].slice(0, 4);
  const date = new Date();
  date.setHours.apply(date, parts);
  return date.getTime();
}

data.sort((a, b) => getAddedTimeValue(a.time) - getAddedTimeValue(b.time));

// For descending:
// data.sort((a, b) => getAddedTimeValue(b.time) - getAddedTimeValue(a.time));

console.log(data)
like image 29
Rajesh Avatar answered Dec 26 '22 00:12

Rajesh