How to sort through multiple array?
-
Hello,
I have a situation where I have two arrays that are associated together
reg array1 = ["apples", "oranges", "bananas"]; reg array2 = ["red", "orange", "yellow"];
if I sort one:
array1.sortNatural(); //apples, bananas, oranges
then I cannot use index to associate array 2 with array1, since array1 has been sorted, whereas array2 has not been sorted. How do I make it so that when array1 is sorted, array2 gets sorted into the same places as array1 is so the data stay together?
Thank you!
-
You'll need to write your own array sorting function, and have it take an additional array (your array2) and apply the same indexing as for array 1.
There are plenty of array sorting algorithms. You might care about whether it's stable (whether the equal elements maintain their original indexes), how it performs for small vs. large arrays etc.
-
@Gudru said in How to sort through multiple array?:
Hello,
I have a situation where I have two arrays that are associated together
reg array1 = ["apples", "oranges", "bananas"]; reg array2 = ["red", "orange", "yellow"];
if I sort one:
array1.sortNatural(); //apples, bananas, oranges
then I cannot use index to associate array 2 with array1, since array1 has been sorted, whereas array2 has not been sorted. How do I make it so that when array1 is sorted, array2 gets sorted into the same places as array1 is so the data stay together?
Thank you!
use objects, and sort an array of them...
reg myArray = [ {"Fruit": "apples", "Colour" : "red"}, {"Fruit": "oranges", "Colour" : "orange"}, {"Fruit": "bananas", "Colour" : "yellow"} ];
-
and if you havent used objects in an array before here is how to reference them
for (f in myArray) { Console.print("my fruit is:" + f.Fruit); Console.print("its colour is:" + f.Colour); }