关于javascript:按自定义顺序排序

Sorting on a custom order

本问题已经有最佳答案,请猛点这里访问。

我想知道如何按自定义顺序而不是按字母顺序对数组进行排序。假设您有这个数组/对象:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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"
}];

在这里我们有三种不同的类型:水果、蔬菜和糖果。现在,我要对这个数组进行排序,确保所有的水果都是第一位的,糖果排在水果之后,蔬菜排在最后。每种类型都需要按字母顺序对其项进行排序。我们将使用类似于sortArrayOnOrder ( ["fruit","candy","vegetable"],"name" );的函数,因此基本上,您将在排序后得到这个数组:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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"
}];

有人知道如何为此创建脚本吗?


改进《消除对妇女一切形式歧视公约》的版本:

1
2
3
4
5
6
7
8
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);
});


试试这个

1
2
3
4
5
6
7
8
9
10
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.
        }
    }
);

同样,你的目标声明是不正确的。Instead of:

ZZU1

Use:

1
2
3
4
{
    type:"fruit",
    name:"banana"
}, // etc

=改为:


抽签接受一个您可以应用自定义输出逻辑的抽签函数。