I have a object array looking something like this:
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
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.
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.
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.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With