Kind of hacky, but it works.
var A = [0.5, 0.6, 0.5, 0.7, 0.8, 0.1];
var B = ['a', 'b', 'c', 'd', 'e', 'f'];
var all = [];
for (var i = 0; i < B.length; i++) {
all.push({ 'A': A[i], 'B': B[i] });
}
all.sort(function(a, b) {
return a.A - b.A;
});
A = [];
B = [];
for (var i = 0; i < all.length; i++) {
A.push(all[i].A);
B.push(all[i].B);
}
console.log(A, B);
jsFiddle.
Output
0.1, 0.5, 0.5, 0.6, 0.7, 0.8
["f", "a", "c", "b", "d", "e"]
Basically, we are making objects with a clear tie between A
and B
within a new array, and then sort()
ing that.
Then I go back and rebuild the original the two arrays.
Update
Már Örlygsson makes a good point in the comments. Instead of producing an object like {A: 0.5, B: 'a'}
, he suggests placing the A
an B
values in arrays like [0.5, 'a']
.
This should be faster, though it will be slightly less readable if needing to debug the all
array. I'll leave this up to you, if you are experiencing performance issues, profile both these methods and choose the fastest.