Answer the question
In order to leave comments, you need to log in
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;
}
function sortFunction(i, ii) {
return i[1]-ii[1];
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question