Sort an ArrayCollection in Flex

Posted on August 12, 2010
by

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: ArrayUtils.as

package classes.utils
{
import mx.collections.ArrayCollection;
import mx.collections.Sort;
import mx.collections.SortField;
 
/**
* Useful functions to manipulate arrays
*
* @author Cyril Mazur cyrilmazur.com
*/
public class ArrayUtils
{
/**
* Sort an arrayCollection by key
* order MUST be either "ASC" or "DESC"
*
* @author Cyril Mazur cyrilmazur.com
* @see http://blog.flexexamples.com/2007/08/05/sorting-an-arraycollection-
using-the-sortfield-and-sort-classes/
*
* @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();
dataSortField.name = 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;
arrayCollection.refresh();
 
/* Return the collection */
return arrayCollection;
}
}
}

Download the source here: ArrayUtils.as

I’m open to any suggestion to improve the code :-)