Sorting on a custom order

后端 未结 4 1354
旧巷少年郎
旧巷少年郎 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:30

    For people looking to simply sort an array of strings in a custom order, try this function below:

    // sorting fn
    const applyCustomOrder = (arr, desiredOrder) => {
      const orderForIndexVals = desiredOrder.slice(0).reverse();
      arr.sort((a, b) => {
        const aIndex = -orderForIndexVals.indexOf(a);
        const bIndex = -orderForIndexVals.indexOf(b);
        return aIndex - bIndex;
      });
    }
    
    // example use
    const orderIWant = ['cat', 'elephant', 'dog'];
    const arrayToSort = ['elephant', 'dog', 'cat'];
    
    
    applyCustomOrder(arrayToSort, orderIWant);
    

    This will sort the array in the order specified. Two sample input / outputs to this function:

    Example 1:

    const orderIWant = ['cat', 'elephant', 'dog'] 
    const arrayToSort = ['mouse', 'elephant', 'dog', 'cat'];
    applyCustomOrder(arrayToSort, orderIWant); 
    console.log(arrayToSort); // ["cat", "elephant", "dog", "mouse"]
    

    Example 2:

    const orderIWant = ['cat', 'elephant', 'dog'];
    const arrayToSort = ['mouse', 'elephant', 'rabbit', 'dog', 'cat'];
    applyCustomOrder(arrayToSort, orderIWant); 
    console.log(arrayToSort); /* ["cat", "elephant", "dog", "mouse", 
    "rabbit"] */
    
    0 讨论(0)
  • 2020-12-09 08:31

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

    0 讨论(0)
  • 2020-12-09 08:32

    Improved version of Cerbrus' code:

    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);
    });
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题