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?
return a.rank - b.rank;, the subtraction will forcerankto be converted to a number (if it can be).waypoints.sort(function(a,b) {return a.rank - b.rank;});seems to work, but I have no idea why. Does this method only work for numbers or would it work for words?12), then that happens. Other strings (e.g. "foo" ->NaN) not so.