0

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?

3
  • 2
    You should be able to do just return a.rank - b.rank;, the subtraction will force rank to be converted to a number (if it can be). Commented Feb 28, 2013 at 5:02
  • 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? Commented Feb 28, 2013 at 5:58
  • 1
    For some version of "work", yes, but probably not how you expect. The comment above has a link to the internal ToNumber algorithm, and the special treatment of strings. Essentially if the string converts to a number literal (e.g. "12" -> 12), then that happens. Other strings (e.g. "foo" -> NaN) not so. Commented Feb 28, 2013 at 9:35

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Worked great, thank you! Seems strange though that sorting a sorted array could unsort it...
Because the first sort is sorting numbers, the second is sorting objects. The algorithm is in ECMA-262.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.