I have an array of objects, and I would like to sort them following these two rules (in order of priority):
The objets whose "departeYet" property is true must be at the beginning The objects must then be sorted in numerical order (the "number" property)
This would be ok:
- true : 005
- true : 007
- true : 027
- false: 009
- false: 020
This is the structure of the part of the objects that interests us:
var notSortedData = {
number: number, // it's a string
departedYet: scheduled_date, // true or false
}
sortedTrains.push(notSortedData);
So, notSortedData is pushed in sortedTrains via a for loop.
Then, I need to sort it:
sortedTrains.sort(function(a, b) {
// sorting algorithm here
});
What should I do? Thanks.
sort
function works and what it's parameter function should return. See the docs. Short answer: you do not need to implement a sorting algorithm, all you need is a compare function.