Here’s how to use the order or a config array to sort another array, using the JavaScript language.
Why use a sorting array?
Sometimes you don't control the original array, and it's easier to define a configuration array rather than do elaborate conditional logic.
Compare indexOf in sort
Here’s a utility function which check the index of each array item with
indexOf, and sorts based on that:
const coreMarkets = [
{ iso2: 'at', name: 'Austria' },
{ iso2: 'ch', name: 'Switzerland' },
{ iso2: 'de', name: 'Germany' },
{ iso2: 'es', name: 'Spain' },
{ iso2: 'fi', name: 'Finland' },
{ iso2: 'gb', name: 'Great Britain' },
{ iso2: 'it', name: 'Italy' },
]
const marketFocus = ['de', 'es', 'it', 'gb', 'ch', 'fi', 'at']
export function sortMarkets(arr: typeof coreMarkets, sortArr: string[]) {
return arr.toSorted(
(a, b) => sortArr.indexOf(a.iso2) - sortArr.indexOf(b.iso2)
)
}
sortMarkets(coreMarkets, marketFocus)Conclusions
This method has been in my tool belt for a while, very handy.