0

I need to sort an array by his inside first element data . my array looks something like that

arr = [[0,"lol"][6,"yo"][5,"comon"]]

After the sorting I need it to be like that :

[[0,"lol"][5,"comon"][6,"yo"]]

0 , 5 , 6 suppose to order the cells and they data they have is irrelevent. Thanks.

5
  • Have you tried anything? Commented Jul 10, 2013 at 10:48
  • 2
    arr.sort(function(a, b) { return a[0] - b[0] }); Commented Jul 10, 2013 at 10:48
  • please post your code? Commented Jul 10, 2013 at 10:49
  • @Givi please place an answer so i can check it Commented Jul 10, 2013 at 10:54
  • @OriGavrielRefael I updated my answer, made it more effective... ;) Commented Jul 10, 2013 at 13:01

3 Answers 3

1

You can try something like this... Live Demo

I made ​​some changes...

  1. Corrected the mistake :
    // before that I'm checking arrays and not a values of it...
    (!isNaN(a) && !isNaN(b)) to (!isNaN(a[0]) && !isNaN(b[0]))
  2. and to ignore case...
    aa = a[0].toString().toLowerCase(); bb = b[0].toString().toLowerCase();

===========================================================

arr.sort(function (a, b) {
    var aa, bb;
    if (!isNaN(a[0]) && !isNaN(b[0])) {
        return a[0] - b[0];
    } else {
        aa = a[0].toString().toLowerCase();
        bb = b[0].toString().toLowerCase();
        return (aa == bb) ? 0 : (aa < bb) ? -1 : 1;
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

I didn't downvote, but in my opinion testing for non-numeric is overkill given the input was specified as numeric. Still, I guess +1 for showing a way to handle non-numerics...
@nnnnnn I updated my answer, making it a more versatile... ;)
1

jsfiddle Link

var arr = [[0,"lol"],[6,"yo"],[5,"comon"]];
arr.sort(function(a, b) {
   return a[0] - b[0];
});

2 Comments

It needs to be return a[0] - b[0]; the sort function isn't supposed to return a boolean.
@OriGavrielRefael Yes, it will be better.
1

Use this code to sort your array..

var arr = [[0,"lol"],[6,"yo"],[5,"comon"]];

arr.sort(function(a, b) {
    if (a[0] == b[0]) {
        return 0;
    } else {
        return a[0] < b[0] ? -1 : 1;
    }
});

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.