Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome - Javascript sorting inconsistently

I'm aware of Chrome's unstable sorting issues, but I'm at a loss on how to address this when sorting strings.

myArray.sort(function(a, b){
        var typeA=a.toLowerCase();
        var typeB=b.toLowerCase();

        return (typeA < typeB) ? -1 : (typeA > typeB) ? 1 : 0;
        });

works fine in FF and Safari, but in Chrome this still returns an incorrect order. That is, Chrome doesn't honor that if typeA == typeB, return 0...it still chooses to move it. Is there a fix out there for dealing with sorting strings?

like image 691
Marcus Avatar asked Jun 20 '26 06:06

Marcus


1 Answers

JS spec doesn't require sorting algorithm to be stable, so you can't count on that.

The only definite ways to solve unstable sorting issue is to either manually code different, stable algorithm or to add one additional unique key to sort on to guarantee that comparison function would always treat two elements as either greater or lesser to each other, but never as equal. Original array index would do.

like image 167
Oleg V. Volkov Avatar answered Jun 22 '26 20:06

Oleg V. Volkov