Reputation: 2146
I'm trying to sort an array of objects by a property rank
which each object has. This seems to be the accepted way of doing it. However, it does not seem to be working correctly.
var waypoints = ig.game.getEntitiesByType(EntityWaypoint); // returns array of objects
// This line tells sort to order by Array[i].rank
waypoints.sort(function(a,b) {return (a.rank < b.rank) ? -1 : (a.rank > b.rank) ? 1 : 0;});
waypoints.sort();
for( var i=0; i<waypoints.length; i++ ) {
console.log(waypoints[i].rank);
}
Console ends up looking like this:
4
1
2
3
5
6
7
I've also tried the following variation which results in the same thing.
waypoints.sort(function(a,b) {return (parseInt(a.rank) < parseInt(b.rank)) ? -1 : (parseInt(a.rank) > parseInt(b.rank)) ? 1 : 0;});
Why isn't this properly sorting an array of objects by the rank
property of each object?
Upvotes: 0
Views: 137
Reputation: 359986
There is nothing wrong with your custom sort. Your first piece of code calls waypoints.sort()
twice. The second sort is mucking with the ordering; remove it.
Upvotes: 3