Sort an ArrayCollection in Flex

Posted on August 12, 2010

As nothing’s as straight forward as PHP, I had to write my own class to sort ArrayCollections. My work was inspired by what Peter Dehaan did.

The method is to be used as follows:

ArrayUtils.sort(games, "playerScore", "DESC", true);

to sort an ArrayCollection of games by player score, with a descending order. The last parameter indicates that we want a numeric sorting rather than a alphabetical sorting.

I encapsulated the method in an ArrayUtils class, but you’re free to do as you wish. That’s because I think I will add more methods to my class in a near future. You can download the class here:

package classes.utils
import mx.collections.ArrayCollection;
import mx.collections.Sort;
import mx.collections.SortField;
* Useful functions to manipulate arrays
* @author Cyril Mazur
public class ArrayUtils
* Sort an arrayCollection by key
* order MUST be either "ASC" or "DESC"
* @author Cyril Mazur
* @see
* @param ArrayCollection arrayCollection
* @param String sortBy
* @param String order
* @param Boolean numericSort
* @return ArrayCollection
public static function sort(arrayCollection:ArrayCollection, sortBy:String,
order:String, numericSort:Boolean):ArrayCollection {
/* Create the sort field and fill it */
var dataSortField:SortField = new SortField(); = sortBy;
dataSortField.caseInsensitive = true;
dataSortField.numeric = numericSort;
/* Set the order, by default it's ascending */
if (order.toUpperCase() == "DESC") {
dataSortField.descending = true;
/* Create the Sort object and add the SortField object
created earlier to the array of fields to sort on. */
var dataSort:Sort = new Sort();
dataSort.fields = [dataSortField];
/* Set the ArrayCollection object's sort property to our
custom sort, and refresh the ArrayCollection. */
arrayCollection.sort = dataSort;
/* Return the collection */
return arrayCollection;

Download the source here:

I’m open to any suggestion to improve the code 🙂

About the author

Cyril Mazur is a serial web entrepreneur with experience in various fields: online dating, forex & finance, blogging, online advertising... who enjoys building things that people like to use.