I was wondering how I can sort an array on a custom order, not alphabetical. Imagine you have this array/object:
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"
}];
In here we have 3 different types: fruit, vegetable and candy. Now I want to sort this array, and make sure that all fruits are first, candies come after fruits, and vegetables be last. Each type need their items to be sorted on alphabetical order. We will use a function like sortArrayOnOrder ( ["fruit","candy","vegetable"], "name" );
So basically, you would end up with this array after sorting:
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"
}];
Anyone an idea how to create a script for this?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…