最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin4浏览0评论

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?

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?

Share Improve this question asked Jun 20, 2011 at 22:58 SarathiSarathi 1,0511 gold badge14 silver badges22 bronze badges 1
  • 2 Having two parallel arrays for your data is a bad idea. Use an array of objects [{name: 'human', type: 'person'}, {name: 'animal', type: 'beast'}] and you don't have to worry about syncing. If you have to sync structures, you're not following the DRY principle. – Ruan Mendes Commented Jun 20, 2011 at 23:14
Add a ment  | 

3 Answers 3

Reset to default 4

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)

  1. 暂无评论