Sorting on a custom order

This question already has an answer here:

  • Sort array of objects by string property value in JavaScript 33 answers

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

    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.


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

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

    上一篇: 如何在打字稿中基于键排序对象数组

    下一篇: 按照自定义顺序排序