21

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


}); 
1
  • 1
    I would split the collection in 2 arrays : 1 with AM strings, 1 with PM strings, then order them separately and display them 1 after each other. Commented Jun 12, 2013 at 11:45

5 Answers 5

48

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);
Sign up to request clarification or add additional context in comments.

2 Comments

This is working just as I wanted . Thanks . I didn't thought to compare using Date object .
but can you tell you how I use this for sorting data got using json . $.getJSON(serviceURL + 'read.php?month_no='+month_no, function(data) { events = data.data; there is events[].event_date in 'yyyy-mm-dd' format and events[].event_time in above givent format
11

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

Comments

6

Implement the sort(compare) function and compare the date string using any arbitrary date :

Array.sort(function (a, b) {
    return Date.parse('01/01/2013 '+a) - Date.parse('01/01/2013 '+b)
});

01/01/2013 is any arbitrary date.

Comments

2
var a = ['9:15 AM', '10:20 AM', '02:15 PM'];

var sort = function(a){
  var sa = [],
      d = new Date(),
      ds = d.toDateString();

  for(var i = 0; i < a.length; i++){
    d = new Date(ds + ' ' + a[i]);
    sa.push(d);
  }

  sa.sort(function(a, b){return a.getTime() - b.getTime();})
  return sa;
}

Comments

1
function sortTimes(arrayOfTimes) {

    return arrayOfTimes.sort((a, b) => {
        const aParts = getNumericParts(a);
        const bParts = getNumericParts(b);

        // Sorts by hour then minute
        return aParts[0] - bParts[0] || aParts[1] - bParts[1];
    });

    function getNumericParts(time) {
        // accounts formats of 9:15 AM and 09:15:30 but does not handle AM/PM in comparison
        return time.split(' ')[0].split(':').map(x => +x);
    }
}

Here's a more concise and performant variation of Dustin Silk's answer. It takes into account formats of 9:15 AM, 09:15, and 09:15:30 though it does not sort based on seconds. You could add that by using || aParts[2] - bParts[2] as a part of the return statement.

sortTimes(['08:00', '09:00', '05:00', '08:15', '08:00']) 
// Output ["05:00", "08:00", "08:00", "08:15", "09:00"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.