Skip to content
Advertisement

Sorting multiple arrays based on one

I have 2 arrays: the first one contains a list of score numbers, and the second contains a list of countries with the same number of elements. Each country is linked with its proper score during the input. So, let’s say the input arrays are the following:

JavaScript

I need the following output:

JavaScript

A possible solution I can know of is to transform the arrays into a single array containing a list of “score=country” pairs. But I wonder if it’s possible to do a miracle with the Array.sort() method, since it accepts a callback function. Any other solutions are welcome too.

Advertisement

Answer

Use a hash as your intuition was leading you to:

JavaScript

Caveats:

  1. Using dfsq’s reverse of this (i.e.,{country:number}) may be better. In the above, the keys (numbers) may be turned into strings, which may have unwanted sort when there are more countries; JavaScript may sort the keys by the first ASCII character like (e.g.,['1','10',…,'19','2','20',…,'29','3',…]).

Benefits:

  1. If the scores are actually IDs, and you are expecting to work with, it makes sense to use that as the key, otherwise if you will be doing lookups by country name to retrieve the score, it makes sense to make the country name the key.
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement