- Home /
Array Ordering
How can I order an array?
For example, I have an array like this:
var food : String[] = ["Cheese", "Butter"];
and another like:
var prices : float[] = [10.99, 2.5];
How can I list them like cheese then butter (price) but not butter then cheese (alphabetic)?
If you like to apply the sort method - you would have to store your data in Lists ins$$anonymous$$d of builtin arrays.
Answer by whydoidoit · Jan 13, 2013 at 02:55 PM
To start with you shouldn't be using two arrays like that if you want to keep the items together - instead make a class:
class FoodAndPrice
{
var food : String;
var price : float;
}
FoodAndPrice[] items;
Then add those to a list or an array (this means when you sort they will be kept together).
To sort it by one of the values you can use Linq:
import System.Linq;
The to get the sorted items into an array from an array or list:
var sortedItems = items.OrderBy(function(i) i.price).ToArray();
var cheapestItemName = sortedItems[0].food;
var cheapestItemPrice = sortedItems[0].price;
Answer by geniuscd · Jan 13, 2013 at 01:15 PM
you can use the Sort() function in the JavaScript myarray.sort()
it will sort them in alphabetical or ascendant order.
for more info you can check http://www.javascriptkit.com/javatutors/arraysort.shtml
Answer by tomekkie2 · Jan 13, 2013 at 01:30 PM
This has been already answered here:
http://answers.unity3d.com/questions/22261/sorting-builtin-arrays.html
Or you culd store your data in Lists instead of builtin arrays and apply the sort() method.