I am trying to sort my array.
The array consists of data in time format.
Array:
'9:15 AM', '10:20 AM', '02:15 PM'
How should I sort it ?
I'm getting this data usig json service & using it to list events in jquery mobile's listview . but I want to sort events by time .
UPDATE: HOW I SORTED DATA FROM JSON BY BOTH DATE AND TIME:
For my particular problem of sorting data got using json by date & time I done like this :
$.getJSON(serviceURL + 'read.php?month_no='+month_no, function(data) {
events = data.data;
events.sort(function(a,b){
a = new Date(a.event_date+' '+a.event_time);
b = new Date(b.event_date+' '+b.event_time);
return a<b?-1:a>b?1:0;
});
});
JavaScript's sort() method As previously mentioned, the Array data structure in JavaScript has a built-in sort() method used to sort the elements of an array. The sort() method works by converting the elements into strings and sorting those string representations of elements lexicographically in ascending order.
Time Complexity We have to loop through every element in the array (let's call it's length "a"); then at each step we have to sort a string (let's call the length of the longest string "s"). The best sorting algorithms (including the version of quick sort we use here) have a time complexity of s * log(s) .
Using the Arrays.util package that provides sort() method to sort an array in ascending order. It uses Dual-Pivot Quicksort algorithm for sorting. Its complexity is O(n log(n)). It is a static method that parses an array as a parameter and does not return anything.
Try this
var times = ['01:00 am', '06:00 pm', '12:00 pm', '03:00 am', '12:00 am']; times.sort(function (a, b) { return new Date('1970/01/01 ' + a) - new Date('1970/01/01 ' + b); }); console.log(times);
My solution (For times formated like "11:00", "16:30"..)
sortTimes: function (array) {
return array.sort(function (a, b) {
if (parseInt(a.split(":")[0]) - parseInt(b.split(":")[0]) === 0) {
return parseInt(a.split(":")[1]) - parseInt(b.split(":")[1]);
} else {
return parseInt(a.split(":")[0]) - parseInt(b.split(":")[0]);
}
})
}
In case someone wanted to know haha
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