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

Array.implement({
	pairedSort: function(other, reverse) {
		if (this.length === other.length) {
			for (var i = 0, len = this.length; i < len; i++) {
				var curr = this&#91;i&#93;;
				var currOth = other&#91;i&#93;;
				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!)

2 thoughts on “Paired sort in JavaScript

  1. Robert says:

    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.

    Reply
    1. Barry van Oudtshoorn says:

      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.

      Reply

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.