Reputation: 1540
So I have an array of objects, and I would like to sort them following these two rules (in order of priority):
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.
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!
Upvotes: 2
Views: 1559
Reputation: 2345
I would suggest to utilize a library such as underscore or lo-Dash, because later you might add more sort conditions or change them and using the library will greatly reduce the noisiness of your code and save you development effort. Assuming lo-Dash is used, the code will be as elegant as follows:
var sortedTrains = [
{ 'number': 5, 'scheduled_date': '2014-10-12 00:00:00'},
{ 'number': 5, 'scheduled_date': '2014-10-12 01:00:00' },
{ 'number': 5, 'scheduled_date': '2014-10-12 02:00:00'},
{ 'number': 6, 'scheduled_date': '2014-10-12 03:00:00' }
];
var result = _.sortBy(sortedTrains, ['number', 'scheduled_date']);
Upvotes: 0
Reputation: 3888
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;
});
Upvotes: 2