How to sort the array of objects by time in javascript

advertisements

I have a object array looking something like this:

  • [0] = { transportnumber: '45', time: '10:28:00', date:"2017-01-16"}
  • [1] = { transportnumber: '45', time: '10:38:00', date:"2017-01-16"}
  • [2] = { transportnumber: '45', time: '10:48:00', date:"2017-01-16"}
  • [3] = { transportnumber: '14', time: '10:12:00', date:"2017-01-16"}
  • [4] = { transportnumber: '14', time: '10:24:00', date:"2017-01-16"}
  • [5] = { transportnumber: '14', time: '10:52:00', date:"2017-01-16"}

The object array will always look like this unsorted. First by transport number and then by time. This due to the api i´m using.

My question is: How i can sort this array only by time?

I´ve tried using the sort function as seen below on my variable where the object array is stored but with no success:

allBuses.sort(function(a,b){
var c = a.time;
var d = b.time;

if(c > d){
return d
}

else return c


You could treat time as string and sort with String#localeCompare.

var data = [{ transportnumber: '45', time: '10:28:00', date:"2017-01-16"}, { transportnumber: '45', time: '10:38:00', date:"2017-01-16" },{ transportnumber: '45', time: '10:48:00', date:"2017-01-16" }, { transportnumber: '14', time: '10:12:00', date:"2017-01-16" }, { transportnumber: '14', time: '10:24:00', date:"2017-01-16" }, { transportnumber: '14', time: '10:52:00', date:"2017-01-16"}];

data.sort(function (a, b) {
    return a.time.localeCompare(b.time);
});

console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }