javascript 按自定义顺序排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14872554/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 22:48:54  来源:igfitidea点击:

Sorting on a custom order

javascriptarrays

提问by RemiDG

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:

在这里,我们有 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"
}];

Anyone an idea how to create a script for this?

任何人都知道如何为此创建脚本?

回答by Bergi

Improved version of Cerbrus' code:

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

回答by Cerbrus

Try this:

试试这个:

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

Also, your object declaration is incorrect. Instead of:

此外,您的对象声明不正确。代替:

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

Use:

利用:

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

So, replace the =signs with :'s.

因此,将=符号替换为:'s。

回答by Matt Randle

Array.sort accepts a sort function where you can apply custom sorting logic.

Array.sort 接受一个排序函数,您可以在其中应用自定义排序逻辑。