Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort object array by time in javascript

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
like image 209
jaikl Avatar asked Jan 16 '17 09:01

jaikl


People also ask

How do you sort data by date and time in JavaScript?

sort( (objA, objB) => Number(objA. date) - Number(objB. date), ); // 👇️ {id: 3, date: Thu Feb 24 2022, // id: 2, date: Fri Feb 24 2023 // id: 5, date: Wed Feb 24 2027} console. log(sortedAsc); // ✅ Sort in Descending order (high to low) const sortedDesc = arr1.

Can you sort objects JavaScript?

To sort the keys of an object:Call the sort() method on the array. Call the reduce() method to get an object with sorted keys.

How do you sort an array of elements in JavaScript?

JavaScript Array sort() The sort() sorts the elements of an array. The sort() overwrites the original array. The sort() sorts the elements as strings in alphabetical and ascending order.


1 Answers

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; }
like image 64
Nina Scholz Avatar answered Nov 11 '22 23:11

Nina Scholz