Zach Smith
Zach Smith

Reputation: 8971

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]; 
});
    
console.log(r)

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)?

Upvotes: 1

Views: 312

Answers (2)

Christoph
Christoph

Reputation: 1630

One problem I see is your compare function.

Returning 0 means that both entries of the array have the same value. Like in a number array when both numbers are the same.

Look at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort for reference.

Quote from there for sorting strings:

items.sort(function(a, b) {
    var nameA = a.name.toUpperCase(); // ignore upper and lowercase
    var nameB = b.name.toUpperCase(); // ignore upper and lowercase
    if (nameA < nameB) {
        return -1;
    }
    if (nameA > nameB) {
        return 1;
    }

    // names must be equal
    return 0;
});

Upvotes: 1

Pointy
Pointy

Reputation: 413866

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]);
});

Upvotes: 2

Related Questions