1

I've 2 or more array

var Arr1 = [1,1,3,2];
var Arr2 = [a,b,c,d];

The idea is to sort the 1st array, that is the one that is the master one, and I wanna reflect the new sorting on second array, so the results well be

var Arr1 = [1,1,2,3];
var Arr2 = [a,b,d,c];

There is any command to do that in a "quick" way?

1

4 Answers 4

4

Zip 'em, sort 'em, unzip 'em. In very plain Javascript:

var zip = [];
for (var i = 0; i < Arr1.length; i++) {
    zip.push([Arr1[i], Arr2[i]]);
}

zip.sort(function (a, b) { return a[0] - b[0]; });

for (var i = 0; i < zip.length; i++) {
    Arr1[i] = zip[i][0];
    Arr2[i] = zip[i][1];
}
Sign up to request clarification or add additional context in comments.

Comments

1

You could use the indices as a temporary array and sort it with the values of arr1. Then map the result to arr2.

var arr1 = [1, 1, 3, 2],
    arr2 = ['a', 'b', 'c', 'd'],
    indices = arr1.map(function (_, i) { return i; });

indices.sort(function (a, b) { return arr1[a] - arr1[b]; });
arr2 = indices.map(function (a) { return arr2[a]; });

console.log(arr2);

ES6

var arr1 = [1, 1, 3, 2],
    arr2 = ['a', 'b', 'c', 'd'];

arr2 = arr1
    .map((_, i) => i)
    .sort((a, b) => arr1[a] - arr1[b])
    .map(a => arr2[a]);

console.log(arr2);

Comments

0

if you use underscore, you can try this idea:

var sorted =_.map(new Array(4), function(i){
    return {
          a:Arra1[i],
          b:Arr2[i]
}
}).sort(function(item){return item.a; })

or js

var sorted = new Array(4).map(function(item,index){
return {
              a:Arra1[i],
              b:Arr2[i]
    }
};
sorted.sort(function(p,b){ return p.a-b.a;})

Arr1 = sorted.map(function(item){return item.a});
Arr2 = sorted.map(function(item){return item.b});

Comments

0

Assuming the two Arrays are Arr1, Arr2 and they have the same length:
1) Combine the two arrays:

var combined = [];
for (var i = 0; i < Arr1.length; i++) {
  combined.push({'arr1': Arr1[i], 'arr2': Arr2[i]});
}

2) Sort together:

combined.sort(function(a, b) {
  return a.arr1 < b.arr1; //ascending based on arr1
});

3) Separate:

for (var i = 0; i < combined.length; i++) {
  Arr1[i] = combined[i].arr1;
  Arr2[i] = combined[i].arr2;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.