A
A
Alexander Kurganov2013-06-25 22:50:06
JavaScript
Alexander Kurganov, 2013-06-25 22:50:06

What's wrong with .sort() in Javascript?

I can’t understand how .sort() works in javascript, I re-read a bunch of resources, I thought I understood, but it wasn’t there, there is a situation in which circumstances drove me, so I can’t change the initial data, I can of course to rebuild the array on the client, but it is not desirable.
The situation is this, there is an array, each element of which, an array with four lines, I need to give the user the opportunity to sort the list on the screen.
Example
The example is greatly simplified, without buttons and progressbars, but this does not change the essence. I checked, the behavior is the same, the conditions were recreated as accurately as possible.
The point is that I can't sort the array by the array[1] value, I sort it with the standard array.sort(sortFunction);
So:

function sortFunction(i, ii) {
    if (i[1] > ii[1])
        return 1;
    else if (i[1] < ii[1])
        return -1;
    else
        return 0;
}

so:
function sortFunction(i, ii) {
   return i[1]-ii[1];
}

The result is the same, in opera, firefox and safari sort by array[0], miracles happen in chrome.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
theaspin, 2013-06-25
@akurganow

The sorting algorithm is not stable in chrome, i.e. the order for the same values ​​is not defined. The simplest option is additional sorting by city if the counter values ​​match.

function sCount(i, ii) {
  var delta = i[1] - ii[1];
  return delta == 0 ? sCity(i, ii) : delta;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question