clubmate.fi

A good[ish] website

Web development blog, loads of UI and JavaScript topics

Sort an array with another array

Filed under: JavaScript— Tagged with: iteration, sorting

Here’s how to use the order or a config array to sort another array, using the JavaScript language.

Why use a sorting array?

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.

Using indexOf

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.

Conclusions

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. Tweet me @intterne if you want to make a correction etc.

  • © 2022 Antti Hiljá
  • About
  • Follow my new Twitter account → @intterne
  • All rights reserved yadda yadda.
  • I can put just about anything here, no one reads the footer anyways.
  • I love u!