2013-02-14 34 views
7

Mi chiedevo come posso ordinare un array su un ordine personalizzato, non in ordine alfabetico. Immagina di avere questo array/oggetto:Ordinamento su un ordine personalizzato

var somethingToSort = [{ 
    type: "fruit", 
    name: "banana" 
}, { 
    type: "candy", 
    name: "twix" 
}, { 
    type: "vegetable", 
    name: "broccoli" 
}, { 
    type: "vegetable", 
    name: "carrot" 
}, { 
    type: "fruit", 
    name: "strawberry" 
}, { 
    type: "candy", 
    name: "kitkat" 
}, { 
    type: "fruit", 
    name: "apple" 
}]; 

Qui abbiamo 3 diversi tipi: frutta, verdura e caramelle. Ora voglio ordinare questo array e assicurarmi che tutti i frutti siano i primi, le caramelle vengano dopo i frutti e le verdure siano le ultime. Ogni tipo richiede che i loro articoli siano ordinati in ordine alfabetico. Useremo una funzione come sortArrayOnOrder (["fruit","candy","vegetable"], "name"); Quindi, fondamentalmente, si finirebbe con questo array dopo l'ordinamento:

var somethingToSort = [{ 
    type: "fruit", 
    name: "apple" 
}, { 
    type: "fruit", 
    name: "banana" 
}, { 
    type: "fruit", 
    name: "strawberry" 
}, { 
    type: "candy", 
    name: "kitkat" 
}, { 
    type: "candy", 
    name: "twix" 
}, { 
    type: "vegetable", 
    name: "broccoli" 
}, { 
    type: "vegetable", 
    name: "carrot" 
}]; 

Chiunque un'idea di come creare uno script per questo?

+0

Vedere anche molti altri "[come ordinare] (http://www.google.de/search?q=stackoverflow+javascript+sort+array+ di + oggetti) "domande – Bergi

risposta

12

Versione migliorata del Codice Cerbrus':

var ordering = {}, // map for efficient lookup of sortIndex 
    sortOrder = ['fruit','candy','vegetable']; 
for (var i=0; i<sortOrder.length; i++) 
    ordering[sortOrder[i]] = i; 

somethingToSort.sort(function(a, b) { 
    return (ordering[a.type] - ordering[b.type]) || a.name.localeCompare(b.name); 
}); 
+0

Hm, la buona idea di costruire un oggetto fuori da sortOrder, rimuove la necessità di usare 'indexOf' ogni volta che viene chiamata la funzione. +1 – Cerbrus

+0

Fantastico. Che funzioni. Grazie! – RemiDG

0

Array.sort accetta una funzione di ordinamento in cui è possibile applicare la logica di ordinamento personalizzata.

2

Prova questo:

var sortOrder = ['fruit','candy','vegetable']; // Declare a array that defines the order of the elements to be sorted. 
somethingToSort.sort(
    function(a, b){        // Pass a function to the sort that takes 2 elements to compare 
     if(a.type == b.type){     // If the elements both have the same `type`, 
      return a.name.localeCompare(b.name); // Compare the elements by `name`. 
     }else{         // Otherwise, 
      return sortOrder.indexOf(a.type) - sortOrder.indexOf(b.type); // Substract indexes, If element `a` comes first in the array, the returned value will be negative, resulting in it being sorted before `b`, and vice versa. 
     } 
    } 
); 

Inoltre, la vostra dichiarazione oggetto non è corretto. Invece di:

{ 
    type = "fruit", 
    name = "banana" 
}, // etc 

Usa:

{ 
    type: "fruit", 
    name: "banana" 
}, // etc 

Quindi, sostituire i cartelli con =: 's.

+0

+1, bello. Vedere la mia risposta per una variante migliorata efficacemente – Bergi

+0

Wups, mi dispiace per il = invece di:. Ho appena scritto un esempio qui, non ho copiato nulla e ho dimenticato di: assegnare i valori. Im troppo usato per usare l'operatore = per assegnare valori haha: P – RemiDG

Problemi correlati