2013-02-14 62 views
7

我想知道如何按自定義順序排序數組,而不是按字母順序排列。想象一下你有這個數組/對象:在自定義訂單上排序

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" 
}]; 

在這裏,我們有3種不同的類型:水果,蔬菜和糖果。現在我想對這個數組進行排序,並確保所有的水果都是第一個,糖果來自水果,蔬菜最後。每種類型都需要按照字母順序對其項目進行排序。我們將使用像sortArrayOnOrder (["fruit","candy","vegetable"], "name");函數所以基本上,分揀後,你最終會與此陣:

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" 
}]; 

任何人的想法如何創建這樣的腳本?

+0

又見許多其他的「[如何排序(http://www.google.de/search?q=stackoverflow+javascript+sort+array+ +對象)「問題 – Bergi 2013-02-14 10:27:33

回答

12

提高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

嗯,從sortOrder構建一個對象的好主意,每次調用函數時都不需要使用'indexOf'。 +1 – Cerbrus 2013-02-14 10:35:35

+0

太棒了。這樣可行。謝謝! – RemiDG 2013-02-14 11:28:55

0

Array.sort接受一個排序函數,您可以在其中應用自定義排序邏輯。

2

試試這個:

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

而且,你的對象的聲明是不正確。相反的:

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

用途:

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

所以,更換=跡象與:的。

+0

+1,很好。看到我的回答,獲得了效率提高的變體 – Bergi 2013-02-14 10:32:52

+0

Wups,對於=而不是:。剛剛在這裏寫了一個例子,沒有複製任何麪食,忘記了:分配值。我也習慣使用=操作符來分配值哈哈:P – RemiDG 2013-02-14 11:26:22