I am trying to sort one array, but have a second array stay in sync with the first.
Example:
var a1 = ["human", "animal", "plant"];
var a2 = ["person", "beast", "nature"];
a1.sort();
After the sort I need to arrays to look like this:
a1 = ["animal", "human", "plant"];
a2 = ["beast", "person", "nature"];
Is there an easy way to do this, Maybe using a custom sort function?
You could zip the 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 x.a - y.a;
});
// unzip
var z;
for (i=0; i<zipped.length; i++)
{
z = zipped[i];
a[i] = z.a;
b[i] = z.b;
}
...but I think @duffymo's got a better suggestion for you. Use an 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;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With