Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
146 views
in Technique[技术] by (71.8m points)

javascript - Sorting on a custom order

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Improved version of Cerbrus' code:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...