Ori Refael
Ori Refael

Reputation: 3018

javascript sort array by inside data

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.

Upvotes: 0

Views: 106

Answers (3)

Givi
Givi

Reputation: 1734

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;
    }
});

Upvotes: 1

naveen
naveen

Reputation: 87

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;
    }
});

Upvotes: 1

z1m.in
z1m.in

Reputation: 1661

jsfiddle Link

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

Upvotes: 1

Related Questions