开发者

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

开发者 https://www.devze.com 2023-03-14 10:32 出处:网络
I am trying to sort one array开发者_高级运维, but have a second array stay in sync with the first.

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;
});


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 the return values to get it perfect


I'd use an associative array and sort the keys. That's what you've got here. I think an associative array is a better encapsulation of the idea.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号