Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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
1  
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. –  Juan Mendes Jun 20 '11 at 23:14

3 Answers 3

up vote 2 down vote accepted

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;
});
share|improve this answer
    
Zipping the array worked perfectly! I would have never thought to do something like that. Thanks for the help! –  Sarathi J. Hansen Jun 21 '11 at 1:55

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

share|improve this answer
    
Having a sort function modify a global array just sounds wrong... But I'm afraid this is the simplest way to do what OP asked for –  Juan Mendes Jun 20 '11 at 23:16

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.