Reputation: 60
I have an array of objects. My object has it's title inside of it as a reference. I need to sort my array of objects in Alphabetical order by title.
Below is what I've been playing with, trying to accomplish this goal. As an example, i stored the title reference on my array objects as index 0. On index 1 i stored an ID reference just to check against the result of my sorted array.
The last output I'm getting from flash, is ordered in such a weird way that makes absolutely no sense to me. Please help! I'm open to different methods of accomplishing the same goal.
//This is an example list of my objects, and their test titles.
var obj = Array("ants", 24);
var obj2 = Array("cants", 29);
var obj3 = Array("xants", 35);
var obj4 = Array("bants", 80);
//Hear I assign each object to an array
var test = Array(obj, obj2, obj3, obj4);
//I create 2 arrays. 1 to store the titles in, and 1 for the object itself.
var alpha_sort = Array();
var obj_index = Array();
for(var i in test){//loop through all properties
alpha_sort.push(test[i][0]);
obj_index.push(test[i]);
}
trace('----- Display unsorted list ------');
for(var i in alpha_sort){//loop through all properties
trace(i+' - '+alpha_sort[i]);
}
trace('----- Display sorted list ------');
alpha_sort.sort(2);
for(var i in alpha_sort){//loop through all properties
trace(i+' - '+alpha_sort[i]+ ' - '+obj_index[i][1]);
}
The Output is:
----- Display unsorted list ------
3 - ants
2 - cants
1 - xants
0 - bants
----- Display sorted list ------
2 - bants - 29
1 - cants - 35
0 - xants - 80
3 - ants - 24
Upvotes: 0
Views: 1192
Reputation: 14406
You can do this by either converting your array values to objects (instead of sub arrays) and using the sortOn
method, or creating a custom sort function.
I'd reccomend to prior: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/2/help.html?content=00000751.html
var test = Array({title: "ants", value: 24}, {title: "cants", value: 29},{title: "xants", value: 35});
test.sortOn("title");
To use a custom sort function:
test.sort(sortTitle);
function sortTitle(a, b):Number {
if (a[0] < b[0]) {
return -1;
} else if (a[0]>a[0]) {
return 1;
} else {
return 0;
}
}
Upvotes: 3