Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IE js sorting array by custom function doesn't work

I have simple custom sorting function in js:

function compareDesc(a, b) {
    return a.value < b.value;
}

I am then trying to sort an array of dictionaries:

var test = [];
test.push({value: 0, foo: "bar"});
test.push({value: 250, foo: "bar"});
test.push({value: 3, foo: "bar"});
test.sort(compareDesc);
alert(test[0].value);
alert(test[1].value);
alert(test[2].value);

It works in Chrome and Firefox where I get:

250
3
0

But in all version of IE I get:

0
250
3

So the sorting doesn't work. Any ideas why?

like image 445
Richard Knop Avatar asked May 08 '26 15:05

Richard Knop


1 Answers

It is better to return 1, 0 and -1 instead of just true and false:

function compareDesc(a, b) {
    if (a.value < b.value){
        return 1;
    }
    else if(a.value > b.value)
    {
        return -1;
    }
    return 0;
}

Here is an example: http://jsfiddle.net/2wwBF/2

P.S. The example of the sort function from JS documentation proposes the following way:

function compareDesc(a, b) {
    return a.value - b.value
}
like image 106
Artem Vyshniakov Avatar answered May 11 '26 04:05

Artem Vyshniakov