JavaScript Sort an array, but synchronize the second array

I am trying to sort one array, but the second array will remain in sync with the first.

Example:

var a1 = ["human", "animal", "plant"]; var a2 = ["person", "beast", "nature"]; a1.sort(); 

After sorting, I need arrays to look like this:

 a1 = ["animal", "human", "plant"]; a2 = ["beast", "person", "nature"]; 

Is there an easy way to do this, possibly using a custom sort function?

+4
source share
3 answers

You can archive arrays before sorting and unzip them after sorting:

 var a = ["human", "animal", "plant"], b = ["person", "beast", "nature"], zipped = []; // zip for (var i=0; i<a.length; i++) { zipped.push({a: a[i], b: b[i]}); } zipped.sort(function (x, y) { return xa - ya; }); // unzip var z; for (i=0; i<zipped.length; i++) { z = zipped[i]; a[i] = za; b[i] = zb; } 

... but I think @duffymo got the best deal for you. Use object / hash / associative array / map.

 var a = [{key: 'human', value: 'person'}, {key: 'animal', value: 'beast'}, {key: 'plant', value: 'nature'}]; a.sort(function (x, y) { return x.key - y.key; }); 
+3
source

Try something like this (untested):

 a1.sort(function(a, b) { if (a > b) { // swap a2[0] and a2[1] var tmp = a2[0]; a2[0] = a2[1]; a2[1] = tmp; return 1 } else if (a < b) { return -1 } else { return 0 } }); 

Live demo

Something like that, play around with return values ​​to achieve perfection

+3
source

I would use an associative array and sort the keys. This is what you have. I think an associative array encapsulates an idea better.

0
source

All Articles