A good[ish] website
Web development blog, loads of UI and JavaScript topics
Here’s how to use the order or a config array to sort another array, using the JavaScript language.
A good way of sorting an array to an arbitrary order, is to use a configuration array where the order is correct.
Say your startup functions in few different countries, and you want to sort the countries in the order of importance, to print them out into a country switcher dropdown or whatever. This is a totally custom metric specific to your situation, something a sorting algorithm can’t deduce.
Here’s a helper function which check the index of each array item with indexOf
, and does the sort
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']
const sortMarkets = (array, sortArray) => {
return [...array].sort(
(a, b) => sortArray.indexOf(a.iso2) - sortArray.indexOf(b.iso2)
)
}
sortMarkets(coreMarkets, marketFocus)
// [
// { "iso2": "de", "name": "Germany" },
// { "iso2": "es", "name": "Spain" },
// { "iso2": "it", "name": "Italy" },
// . . .
// ]
Note that you need to copy it [...array].sort()
or you might mutate the original array. You can also use array.slice().sort()
for that.
This method has been in my tool belt for a while, very handy.
Hope this was helpful. Thanks for reading! 🙇♂️
Comments would go here, but the commenting system isn’t ready yet, sorry.