user2020835
user2020835

Reputation: 1

how to make sort function in javascript behave like mysql order by

I'm trying to sort a multidimensional array. what should i put on the callback of javascript .sort() function to make it behave like mysql order by?

Example. Using mysql order by, result:

acx, 
acx abx,
acx acx,
S&P/ASX 20

Using sort function in js, result:

S&P/ASX 20,
acx, 
acx abx,
acx acx

Thank you.

Upvotes: 0

Views: 1260

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1075079

It's unclear what your multiple dimensions are, but your examples look like they're just sorted without case sensitivity.

In any case, to get custom behavior, what you do is pass a function into sort that compares elements, returning -1, 1, or 0. So for instance:

yourArray.sort(function(a, b) {
    a = a.toLowerCase();
    b = b.toLowerCase();
    if (a < b) {
        return -1;
    }
    if (a > b) {
        return 1;
    }
    return 0;
});

If you're comparing an array of arrays, within the comparison function, you'd compare the various entries in the two arrays you were given in a and b.

Upvotes: 0

georg
georg

Reputation: 215009

The problem is that sorting in JS is case-sensitive. To get around that, provide a function as an argument to sort, which should compare upper-cased (or lower-cased for that matter) versions of strings.

function cmp(x, y) {
    return x > y ? 1 : x < y ? -1 : 0;
}

a = ["S&P/ASX 20","acx", "acx abx","acx acx"]

a.sort(function(x, y) {
    return cmp(x.toUpperCase(), y.toUpperCase())
})

Upvotes: 4

Related Questions