Sort the array of objects following several rules in javascript

advertisements

So I have an array of objects, and I would like to sort them following these two rules (in order of priority):

  1. The numbers must be in numerical order
  2. The times must be in chronological order

So, I want the objects not only to be sorted by numbers, but to be also be sorted by time. For example, this would be ok.

  • 005: 2am
  • 005: 3am
  • 005: 4am
  • 006: 2am
  • 006: 3am

This is the structure of the part of the objects that interests us:

var notSortedData = {
                        number: number, // it's a string
                        scheduled_date: scheduled_date, // the format is "YYYY-MM-DD HH:MM:SS"
                    }

                    sortedTrains.push(notSortedData);

So, notSortedData is pushed in sortedTrains via a for loop. Then I do this, but it is not enough (as it doesn't respect my second condition):

// sorts all the numbers numerically
        sortedTrains.sort(function(a, b) {
            return parseInt(a.number) - parseInt(b.number);
        });

What do I need to do to make sure that my second condition is also respected? Thanks!


You can try this:

sortedTrains.sort(function(a, b) {
    // We parse the numbers
    var num1 = parseInt(a.number), num2 = parseInt(b.number);
    if (num1 != num2) return num1 - num2; // Return the difference IF they are not equal
    var date1 = new Date(a.scheduled_date), date2 = new Date(b.scheduled_date);
    // We only get here if the numbers are equal
    return date1 - date2;
});