Sorting on a custom order

后端 未结 4 1431
旧巷少年郎
旧巷少年郎 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"] */
    

提交回复
热议问题