按照自定义顺序排序

这个问题在这里已经有了答案:

  • 通过JavaScript中的字符串属性值排序对象数组33个答案

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

    尝试这个:

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

    另外,你的对象声明是不正确的。 代替:

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

    使用:

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

    因此,更换=与体征:的。


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

    链接地址: http://www.djcxy.com/p/19323.html

    上一篇: Sorting on a custom order

    下一篇: JavaScript sort array by multiple (number) fields