Sometimes, you’ll have two arrays of associated data, and you’ll need to sort them. You can’t just call sort() on both arrays, because that will potentially break the associations between them. What you need is a way to sort one of the arrays, and shuffle the elements of the second array to match. Here’s a simple MooTools function that does just that (using quicksort):
[sourcecode language=”javascript”]Array.implement({
pairedSort: function(other, reverse) {
if (this.length === other.length) {
for (var i = 0, len = this.length; i < len; i++) {
var curr = this[i];
var currOth = other[i];
var j = i - 1;
while ((j >= 0) && (this[j] > curr)) {
this[j + 1] = this[j];
other[j + 1] = other[j];
j–;
}
this[j + 1] = curr;
other[j + 1] = currOth;
}
}
if (reverse) {
this.reverse();
other.reverse();
}
return this;
}
});[/sourcecode]
Using this function is quite straightforward:
[sourcecode language=”javascript”]var alpha = [3,2,1,6,5,4];
var beta = [1,2,3,4,5,6];
alpha.pairedSort(beta);
// alpha == [1,2,3,4,5,6]
// beta == [3,2,1,6,5,4][/sourcecode]
When would this actually be useful? Let’s say you’ve got an object which maps numeric assessment scores to an alphabetic grade:
[sourcecode language=”javascript”]var mapping = {
‘A’: 80,
‘B’: 60,
‘C’: 40,
‘D’: 20,
‘E’: 0
}[/sourcecode]
Unfortunately, objects in JavaScript have no intrinsic order on their keys — this is because they’re essentially just hashmaps. What we need to do to be able to make use of these data, then, is create an array of keys, and one of values, and then sort them. The pairedSort() function allows us to do this easily. (In fact, it’s for this exact application that I wrote the method!)
Leave a Reply