- Home /
Sort Multiple Arrays By Their Length
I have multiple arrays:
I need to sort the arrays by their length. Eg:
How to find out which one is the largest, the second largest, the third largest, and the least array?
Answer by whydoidoit · Jun 26, 2012 at 01:09 PM
You can do it like this:
import System.Linq;
import System.Collections.Generic;
var arrays = new List.<Array>();
arrays.Add(arr_a);
arrays.Add(arr_b);
arrays.Add(arr_c);
arrays.Add(arr_d);
var sortedArrays = arrays.OrderBy(function(a) { return a.length; }).ToList();
var shortestArray = sortedArrays[0];
var nextShortest = sortedArrays[1];
I have to say using Array is not a good idea in Unity Script - there are a lot of better collection classes (like the ones I've used here). You should use a strongly typed collection where possible or a List implementation.
I'm sorry, after trying this code, I got errors:
"ArgumentOutOfRangeException: Argument is out of range. Parameter name: index"
When I tried to print the "nextShortest" variable, I got:
"Null UnityEngine.$$anonymous$$onoBehaviour:print(Object)"
I attached the Javascript code to the $$anonymous$$ain Camera. I only added "print(nextShortest);" line:
What went wrong?
Did you put it inside a function? You didn't in your jsfiddle example...
function Start() {
var arrays = new List.<Array>();
....
}
No problem. Just remember Unity Script really isn't Javascript. It just looks a bit like it... (and unfortunately is officially called JavaScript which really doesn't help)