ak85
ak85

Reputation: 4264

js sorting by multiple columns not working in IE and Safari

In this question the data is sorted by most then if most is equal it is sorted by who picked more fruit when the two workers worked on the same day. as shown below

    var workers = [
        {"id":"111","name":"April", "most":"7","sd-111222":"1","sd-111333":"2","sd-111444":"2","sd-111555":"2"},
        {"id":"222","name":"Bruno", "most":"7","sd-111222":"2","sd-222333":"1","sd-222444":"2","sd-222555":"2"},
        {"id":"333","name":"Carlos","most":"6","sd-111333":"1","sd-222333":"2","sd-333444":"2","sd-333555":"1"},
        {"id":"444","name":"Dwayne","most":"5","sd-111444":"1","sd-222444":"1","sd-333444":"1","sd-444555":"2"},
        {"id":"555","name":"Ed",    "most":"5","sd-111555":"1","sd-222555":"1","sd-333555":"2","sd-444555":"1"}
    ];

        workers.sort(function(a,b) {
            return (a.most == b.most)
                    ? (b["sd-" + a.id + b.id] - a["sd-" + a.id + b.id])
                    : (b.most - a.most);               
        });
    workers.forEach(function(elm){
        console.log(elm["id"] + " " +elm["name"]);
    });

In FF/Chrome/Android/Chrome for Android this outputs.

    222 Bruno
    111 April
    333 Carlos
    444 Dwayne
    555 Ed

In Safari and IE11 (had to change to alert to see the data) and chrome for IOS only I get as the secondary sort isn't getting applied

    111 April
    222 Bruno
    333 Carlos
    444 Dwayne
    555 Ed

See fiddle.

Why is this? What don't these browsers support? I read the documentation about forEach which doesn't mention any support issues in these browsers, but I presume it isn't an issue with foreach as the sort is happening before hand?

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

Upvotes: 1

Views: 59

Answers (1)

Wayne
Wayne

Reputation: 60414

You are relying on the order of arguments a and b to the callback supplied to sort when you attempt to lookup information in workers:

b["sd-" + a.id + b.id] - a["sd-" + a.id + b.id] 

This ordering is not predictable and does not appear to be consistent across browsers. On Firefox, I get the following look-ups:

sd-111222 
sd-444555

On Safari, I get these (which are the reverse order do not exist):

sd-222111
sd-555444

You shouldn't rely on this ordering. All you know is that you are comparing some element from the array called a to some other element in the array called b. You can't be sure of anything else.

Upvotes: 1

Related Questions