timo
timo

Reputation: 2169

Javascript sort() using the arguments as property selectors for comparison produces weird results on Chrome

I've got an array of strings called countKeys which contains values that correspond to the keys of an object which in turn contains an integer.

I'm trying to sort the array with keys (countKeys) in accordance to their key value in the object (count).

Array with (string )keys:

var countKeys = ["0","6","8","10","12","13","14","17","18","19","22","27","30","35","39","48","50","51","55","58","61","66","76","88","94","107","108","109"];

Object with integer values that I'm trying to compare:

var count = {"0":5,"6":1,"8":3,"10":3,"12":2,"13":3,"14":3,"17":3,"18":2,"19":2,"22":2,"27":1,"30":1,"35":1,"39":1,"48":1,"50":1,"51":2,"55":2,"58":2,"61":1,"66":1,"76":2,"88":1,"94":1,"107":1,"108":1,"109":1};

I'm using the following sort function:

countKeys.sort(function(a, b) {
    return count[b] - count[a];
});

I'm expecting the following result for countKeys:

["0","8","10","13","14","17","12","18","19","22","51","55","58","76","6","27","30","35","39","48","50","61","66","88","94","107","108","109"]

On Firefox and IE, this works, on Chrome however, I'm getting unexpected results:

["0","10","13","14","17","8","76","12","19","22","51","55","58","18","6","48","50","109","27","30","61","66","35","88","94","107","108","39"]

How do I get the same result on Chrome as I'm getting on other browsers?

JSFIDDLE

Upvotes: 1

Views: 36

Answers (1)

Sebastian Simon
Sebastian Simon

Reputation: 19505

It looks like you want to sort by two properties:

  1. The values in count (numerically)
  2. The keys in count (numerically)

You currently only sort by value, but since each browser has a different sorting stability (i.e. whether or not to swap around equal elements), you’ll get different results. Sort by both properties like this:

countKeys.sort(function(a, b) {
  return count[b] - count[a] || b - a;
});

This way, if count[b] - count[a] is 0 (i.e. the values are equal), it proceeds to compare a and b (i.e. the keys) directly.

Upvotes: 2

Related Questions