- Home /
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.
Answer by skovacs1 · Jul 16, 2010 at 03:01 PM
It's very simple as burnumd said. If one of these answers solved your problem, please mark it as the accepted answer.
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);
}
Thanks skovacs, sorry for leaving the question up for a while. $$anonymous$$y internet access has been dodgy so I haven't had an opportunity to check up on it until now.
Answer by raul corrales · Mar 24, 2011 at 05:23 PM
This works if you are interest it http://www.youtube.com/watch?v=3560eDQ8shw
Your answer
![](https://koobas.hobune.stream/wayback/20220613064903im_/https://answers.unity.com/themes/thub/images/avi.jpg)