Sorting on a custom order

后端 未结 4 1459
旧巷少年郎
旧巷少年郎 2020-12-09 08:28

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\"         


        
4条回答
  •  孤街浪徒
    2020-12-09 08:36

    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.

提交回复
热议问题