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\"
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"] */