Paired sort in JavaScript

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!)

Comments

2 responses to “Paired sort in JavaScript”

  1. Robert Avatar

    Hello

    Thanks for the post 🙂

    A few things:
    * You should have your for loop be like this:
    for(var i=0,len=this.length;ihttp://www.telparia.com/badLayout.png

    If I reduce the horizontal size of the browser to be smaller, then things look correct.

    1. Barry van Oudtshoorn Avatar

      Hi Robert,

      Glad you found it useful! Yes, I have seen that pattern in for loops, and I do use it sometimes. Given that a sort() method is meant to be fast, I’ve updated the code to match. 🙂 Yes, my current theme has some issues… The idea is that it automatically splits into multiple columns to make reading easier, but that causes a whole slew of display issues, as you’ve noticed. I’m hoping to do a new design soon, which will fix the issue.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.