2

I have this sorting function, but which i use to sort a table, i can sort by dates (which i have removed for simplicity) and strings, but intergers are acting wierd, a common case is that all values could be 0, which will give the array

[0,0,0,0]

this works perfectly in firefox but not in chrome, it changes the order of the rows in my table although they are equal, i have even followed the ECMA standards. Why do chrome change the order anyway? I have also tried using

return (ascending_order ? a - b : b - a)

But with the same result as my more general approach to work with different data types

arr.sort(function(a, b){
    var onlydigitsRegex = new RegExp("\d+","g");
    if (a.match(onlydigitsRegex) && b.match(onlydigitsRegex)) {
      a = parseInt(a);
      b = parseInt(b);
    } else {
      a = a.toLowerCase();
      b = b.toLowerCase();
    }
    return (a === b) ? 0 : (ascending_order ? ((a > b) ? 1 : -1) : ((a < b)? 1 : -1));
    });
  • What's `a_value` and `b_value`? Post where you set them – blgt Jan 13 '15 at 15:45
  • 5
    Javascript's `array.sort()` is not guaranteed to be stable - that is, you shouldn't rely on same-valued items retaining their original order. The fact that they happen to stay the same in Firefox is nice, but could change - and still be within the standards - in a future version. See http://stackoverflow.com/questions/3026281/array-sort-sorting-stability-in-different-browsers for more on stability across browsers, and http://stackoverflow.com/questions/1427608/fast-stable-sorting-algorithm-implementation-in-javascript for discussion of enforcing stability. – Paul Roub Jan 13 '15 at 15:45
  • 1
    Array.prototype.sort is not guaranteed to be stable. – mbcrute Jan 13 '15 at 15:45
  • 1
    possible duplicate of [Array.sort() is producing unexpected results when elements are equal?](http://stackoverflow.com/questions/27071942/array-sort-is-producing-unexpected-results-when-elements-are-equal) – Paul Roub Jan 13 '15 at 15:52

0 Answers0