Zach Smith Zach Smith -4 years ago 187
Javascript Question

Javascript sort callback not working on all browsers

I have the following code:

var r = [
['Pipe repair', '3 Bravo', 'Household Baker'],
['New connection', '5 Delta', 'Household Griffith'],
['Pipe repair', '3 Bravo', 'Household Baker'],
r = r.sort(function(a, b) {
return (a[0] > b[0]) ? 1: 0;
// EDIT: I mistakingly copied newer code than the original code I was testing. However the answer was still on point.
// The original code (that worked in Chrome but not Safari or my Rhino environment):
// return a[0] > b[0];


Google Chrome produces a sorted output, as does node.js. However Safari does not (and probably older versions of firefox do not either). This script is being run by the Rhino interpreter within an Android app

How can I achieve this same sort across all browsers (I'm making the assumption that that will solve the problem on the platform where this script is being executed)?

Answer Source

The callback you pass to .sort() should return:

  • -1, if the first argument should sort before the second;
  • 0, if the arguments have the same sort order;
  • 1, if the second argument should sort before the first.

Your callback is basically giving bad answers to the sort mechanism in Safari, so the sort process gets confused. Specifically, your callback returns 0 when the keys are the same and when the second key is less than the first.

For comparing strings, you can use .localeCompare() in modern browsers (basically all of them I know of):

r = r.sort(function(a, b) {
    return a[0].localeCompare(b[0]);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download