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:

var scores = [2, 5, 3, 1, 4];
var countries = ["Canada", "Macau", "Sweden", "France", "China"];

I need the following output:

scores = [1,2,3,4,5]
countries = [ "France", "Canada", "Sweden", "China", "Macau" ]

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:

 
var scores = [2, 5, 3, 1, 4];
var countries = ["Canada", "Macau", "Sweden", "France", "China"];

var score = {};
for( var i=0,n=scores.length; i<n; i++){
  score[scores[i]] = countries[i];
}

for( var key in keys=Object.keys(score).sort() ){
  var prop = keys[key];
  console.log(prop, score[prop]);
}

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