Paired sort in JavaScript

2010-08-19 – 10:42am

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

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;
	}
});

Using this function is quite straightforward:

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]

When would this actually be useful? Let’s say you’ve got an object which maps numeric assessment scores to an alphabetic grade:

var mapping = {
  'A': 80,
  'B': 60,
  'C': 40,
  'D': 20,
  'E': 0
}

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

2010-08-20 – 2:30 am

Hello

Thanks for the post :)

A few things:
* You should have your for loop be like this:
for(var i=0,len=this.length;i

This way your only fetching the length once rather than every iteration.

* My system has a 1920x1200 display and your blog layout messes up on it.
I've taken a screenshot: http://www.telparia.com/badLayout.png

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

2010-08-20 – 9:10 am

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.

Add your voice