我想知道如何按自定義順序排序數組,而不是按字母順序排列。想象一下你有這個數組/對象:在自定義訂單上排序
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"
}];
任何人的想法如何創建這樣的腳本?
又見許多其他的「[如何排序(http://www.google.de/search?q=stackoverflow+javascript+sort+array+ +對象)「問題 – Bergi 2013-02-14 10:27:33