Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort string array containing time in format '09:00 AM'?

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;
       });


}); 
like image 917
user2458935 Avatar asked Jun 12 '13 11:06

user2458935


People also ask

How do I sort an array of date strings?

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.

What is the time complexity of sorting an array of strings?

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) .

How do you sort a number in an array of strings?

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.


2 Answers

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); 
like image 119
Shobhit Sharma Avatar answered Oct 11 '22 05:10

Shobhit Sharma


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

like image 21
Dustin Silk Avatar answered Oct 11 '22 03:10

Dustin Silk