Swailem95 Swailem95 - 1 year ago 57
Javascript Question

Why isn't this sorting function working in Safari?

I wrote a function that sorts an array of arrays based on the second element of each subarray. For example:


var x = [['car', 10], ['dog', 20], ['horse', 2]]

Should return
[[ 'dog', 20 ], [ 'car', 10 ], [ 'horse', 2 ]]

I tried this function in Chrome and Firefox and it works just fine. For some reason when I try it out in Safari the resulting array isn't sorted. Why is this happening and what can I do to fix it?

Here is the function:

x = x.sort(function(a,b){
return a[1] < b[1];

Answer Source

You need to return a value smaler than zero, zero or greater than zero. Please see the documentation probably here.

This proposal returns the difference of the values of the items which are acually compared. An while the sortorde is descrending, we need to subtract value of a from b.

function(a, b){
    return b[1] - a[1];


var x = [['car', 10], ['dog', 20], ['horse', 2]];
    return b[1] - a[1];
document.write('<pre>' + JSON.stringify(x, 0, 4) + '</pre>');

Btw, no need to assign the result. Sorting is working in place.