- Home /
Sort() javascript arrays
I have a javascript that holds some items for my game. The items all have a script attached, and variables that determine how many there are and what type of item it is.
I was wondering if it was possible to use Sort() to arrange the items in the array so that I could sort it by type, and then by the object's name, both are contained within the script.
I've looked at the documentation for sort, and it's not very helpful.
http://unity3d.com/support/documentation/ScriptReference/Array.Sort.html
searching on the internet, I've been able to find some hints that what I want might be possible, but nothing that is really usable.
Answer by jonas.du · Sep 22, 2011 at 07:56 PM
If you use generic lists instead of unity arrays you have a lot more possibilities. There is a List.Sort (Generic Comparison) method where you can provied a custom comparison.
Read the part "Generic Lists" in this blog post (very helpful!).
Here the full documentation for Generic Lists.
I'm not sure if you can use the extension methos in unity but if, you could solve your problem as mentioned in this question.
Alright this seems like it might work, can you use it in javascript? I have a very long script that I'm using and to rewrite it in C# would be less than ideal.
This works in javascript too, check out the blog post in the answer.
var myList = new List.<Type>();
When I try and change my array to a generic list it says that
"List does not devote a valid type."
Is this a pro feature, or do I have to do something besides just declare it?
Also, I found this on while looking up more on Javascript Arrays
http://www.javascriptkit.com/javatutors/arraysort2.shtml
however to sort strings, you need to compare them, unity does not allow this.
"$$anonymous$$issing $$anonymous$$ethod Extension String.opLess than" (or something along those lines)
Is there a way to make this work?