2010-11-09 4 views
1

J'ai un tableau multidimensionnel que j'aimerais trier par deux facteurs: d'abord l'état puis la ville par ordre alphabétique. Comment puis-je les trier par ordre alphabétique en fonction de ces deux facteurs? Premier état, puis ville? Je sais comment le faire juste être un facteur, mais pas deux ..Trier Tableau multidimensionnel par deux critères?

Répondre

2
locations.sort(function(x, y) { 
    if (x[1] > y[1])  // if you want to sort by abbreviation, 
    return 1;   // use [2] instead of [1]. 
    else if (x[1] < y[1]) 
    return -1; 
    else if (x[0] > y[0]) 
    return 1; 
    else if (x[0] < y[0]) 
    return -1; 
    else 
    return 0; 
}); 
+0

Excellent! Juste ce dont j'avais besoin. Merci beaucoup! – nmuntz

1

Vous pouvez utiliser la bibliothèque "LINQ for JavaS cript". Bibliothèque très utile.

1

Utilisez un rappel de tri personnalisé:

locations.sort(function(a, b) 
{ 
    if (a[1] < b[1]) 
    { 
     return -1; 
    } 
    if (a[1] > b[1]) 
    { 
     return 1; 
    } 
    if (a[0] < b[0]) 
    { 
     return -1; 
    } 
    if (a[0] > b[0]) 
    { 
     return 1; 
    } 

    return 0; 
}); 
+0

@Fixix: voir ma modification :) –

1

Essayez ceci:

locations.sort(function(a, b){ 
    var cmp = function(x, y){ //generic for any sort 
    return x > y? -1 : x < y ? 1 : 0; 
    }; 
    return [cmp(a[1], b[1]), cmp(a[0], b[0])] < 
     [cmp(b[1], a[1]), cmp(b[0], a[0])] ? 1 : -1; 
}); 

Si vous voulez sor descendant sur la ville, par exemple, vous pouvez utiliser -cmp(...) au lieu de cmp(...)

1

Vous pouvez le faire avec moins d'ifs - peut faire la différence si vous avez beaucoup de villes.

var locations= [ 
    ['Baltimore','Maryland','MD'], 
    ['Germantown','Maryland','MD'], 
    ['Rockville','Maryland ','MD'], 
    ['San Francisco','California','CA'], 
    ['San Diego','California','CA'] 
    ]; 

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

//alert(locations.join('\n')) 
locations.join('\n') 

/* returned value: (String) 
San Diego,California,CA 
San Francisco,California,CA 
Baltimore,Maryland,MD 
Germantown,Maryland,MD 
Rockville,Maryland ,MD 
*/