Chrome’s javascript sort array function is different, yet proper

Chrome’s javascript sort function behaves more like the ECMA standards than the sort function implemented in other browsers (like Firefox, IE, etc), which try to maintain some backwards compatibility with legacy javascript code.

Generally, when sorting an array, I’ve always found the following (incorrect) code:

result.sort(function(a,b) { return a > b } );

According to the ECMA standards, the right way to do it is not to return true or false, like the above function, but to return -1, 0, or 1, depending on how the two strings compare, like the following:

function sortfn (a,b) {
	var upA = a.toUpperCase();
	var upB = b.toUpperCase();
	return (upA < upB) ? -1 : (upA > upB) ? 1 : 0;
}

1 thought on “Chrome’s javascript sort array function is different, yet proper”

  1. I still have a problem with Chrome. If I sort column one, than column two, the first column is not ordered anymore. Example:
    A A
    A B
    B A
    B B
    C A
    C B
    After sort on column two:
    A A
    C A
    B A
    C B
    A B
    B B
    In IE it works fine.

Leave a Comment