0

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.

1
  • Search for [javascript] string sort case. Commented Mar 26, 2013 at 7:11

2 Answers 2

4

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())
})
Sign up to request clarification or add additional context in comments.

2 Comments

It works :) thanks a lot. i didn't figure out that the problem was just js is case sensitive. stupid me.
@user2020835: no problem )) BTW, sorts in mysql could be either way, depending of what collation you use.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.