Sorting by multiple variables

I've figured out how to create a custom class in Javascript that extends IComparable and allows me to sort an array filled with these by a single variable, but my problem is that I need this class to sort by 3 different numbers, rather than just one.

So, let's call my class PriorityEntry, and every instance of this class has a set of a, b, c, d, and e variables. I want to populate an array with instances of PriorityEntry and then sort them by the a variable. Whenever a is equal between the two (which will happen a lot) I want to then compare between the b variables, which if they are similar (which will happen sometimes) then I want to finally compare the c variables (which are randomly determined numbers, to avoid similarity. If these turn out to be similar on occasion I could probably add a fourth variable to sort by which is also randomly determined.)

I just don't get how you can do a more complicated sort than the single-variable comparisons, and if anybody can help me in this area I'd be incredibly grateful.

Here's a .NET forum user's similar problem. Essentially, in your `CompareTo`, do whatever sort you want on a but don't return it yet. If they're equal, do your secondary/tertiary/quaternary sort as necessary.

If you were looking some code (too lazy to translate C# to js?) or couldn't understand burnumd's linked response, it will look something like this (if you are using the IComparable interface and not the Comparable implementation (which wouldn't have to check the argument type)):

Unity mono

``````public int CompareTo(object other)
{
if (!(other is PriorityEntry))
{
throw new ArgumentException("object is not a PriorityEntry");
}
PriorityEntry PEOther = other as PriorityEntry;
if( a != PEOther.a ) return a.CompareTo(PEOther.a);
if( b != PEOther.b ) return b.CompareTo(PEOther.b);
if( c != PEOther.c ) return c.CompareTo(PEOther.c);
if( d != PEOther.d ) return d.CompareTo(PEOther.d);
return e.CompareTo(PEOther.e);
}

``````

Unity js

``````function CompareTo(other : System.Object) : int
{
if (!(other instanceof PriorityEntry)) return;
var PEOther : PriorityEntry = other;
if( a != PEOther.a ) return a.CompareTo(PEOther.a);
if( b != PEOther.b ) return b.CompareTo(PEOther.b);
if( c != PEOther.c ) return c.CompareTo(PEOther.c);
if( d != PEOther.d ) return d.CompareTo(PEOther.d);
return e.CompareTo(PEOther.e);
}

``````

This works if you are interest it http://www.youtube.com/watch?v=3560eDQ8shw