Steven Lu
Steven Lu

Reputation: 43517

Safari browser Javascript array seems to sort strings incorrectly

In the Safari console:

var x = ["20", "21"]; x.sort(function(a,b){return b > a}); x
> ["20", "21"]

Chrome:

var x = ["20", "21"]; x.sort(function(a,b){return b > a}); x
> ["21", "20"]

This works as expected in Safari, though (matches Chrome):

"20" > "21"
false

Scratching my head.

Upvotes: 0

Views: 387

Answers (2)

Steven Lu
Steven Lu

Reputation: 43517

The comparison callback function must return a number instead of just true/false. This is very different from in other languages where you can just provide a "less than" function for the purpose of comparison in sorting.

The differing implementations of the sort() in these two browsers results in the differing observed results...

The body of the sort function should just be return b - a.

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386746

Array#sort need a callback for the type you want to sort.

Basically you need to use number for sorting, because string sorts strings and not numerical. The first sorts by string and the second by numerical values.

var x = ["20", "21", "2", "100", "10", "1", "3", "30"];

x.sort();
console.log(x);

x.sort(function (a, b) {
    return a - b; // implicit casting to Number
});
console.log(x);

Upvotes: 1

Related Questions