Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Sort an Array, but keep a second array in sync

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?

like image 417
Sarathi Avatar asked Feb 24 '23 20:02

Sarathi


1 Answers

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;
});
like image 73
Matt Ball Avatar answered Feb 26 '23 08:02

Matt Ball