DaveDev
DaveDev

Reputation: 42195

JS `array.sort` failing in IE6 because its compared values are not numbers. How to resolve?

I have the following sort function which attempts to sort the items based on whether they start with a value entered into a text box.

items.sort(function(a, b) {
    var aStart = a.name.match(new RegExp('^' + textEntered, 'i')) || [];
    var bStart = b.name.match(new RegExp('^' + textEntered, 'i')) || [];

    if (aStart.length != bStart.length) {
        return bStart.length - aStart.length;
    }
    else {
        return b.name - a.name; // error because these aren't numbers
    }

    return 0;
});

This works in every browser I've tried it in, except for IE6, which returns an error stating that it expected a number.

I tried to implement the suggested fix from this article, which suggests "Don’t reuse the argument variables inside of an Array sort function.": http://www.zachleat.com/web/array-sort with the following:

items.sort(function(a1, b1) {

    var a, b;
    a = a1;
    b = b1;

    var aStart = a.name.match(new RegExp('^' + textEntered, 'i')) || [];
    var bStart = b.name.match(new RegExp('^' + textEntered, 'i')) || [];

    if (aStart.length != bStart.length) {
        return bStart.length - aStart.length;
    }
    else {
        return b.name - a.name;
    }

    return 0;
});

but it doesn't have any effect. Has anyone had to deal with this before? What's the best fix for this issue?

Upvotes: 1

Views: 264

Answers (1)

alex
alex

Reputation: 490433

If you want the comparison between strings and wish to return -1, 0 or 1, use localeCompare().

return a.name.localeCompare(b.name);

Upvotes: 1

Related Questions