ArrayCollection weirdness

I ran into a head-scratcher today…

How can this code:

var index:Number = rows.getItemIndex(partition.placeholderRow );trace( index + " " + (rows.getItemAt(0) === partition.placeholderRow ) );

give this output?

-1 true

rows is an ArrayCollection with one element. partition.placeholderRow exists and is a valid object. I haven’t mucked around with rows.source at all.

Answer follows in comment (so you don’t peek ahead and cheat!)

3 Responses to “ArrayCollection weirdness”


  1. 1 Marc

    The array collection had a custom sort order applied.

    That custom sort has a compare function set. The compare function didn’t handle the a==b element correctly.

    Now, the ArrayCollection class will use your compare function when you call getItemIndex so it can do a quick binary search instead of a long linear search.

    So using our bad sorting compare function, it never found anything equal, and you got that weirdness.

  2. 2 JabbyPanda

    In my case getItemIndex returns -1 when it should not even when simple custom Sort is applied to the collection, without custom compare function, e.g:

    var sortProjects : Sort = new Sort();
    sortProjects.fields = [new SortField("name", true, false)];
    projects.sort = sortProjects;
    projects.refresh();

    ———————–
    later in the code
    ———————–

    var projectInfo : ProjectInfo = projects.getItemAt(1);
    projectInfo.name = “New name”;
    var index : int = projects.getItemIndex(projectInfo); // returns -1

  3. 3 JabbyPanda

    I’ve had figured out my problem with using ‘getItemIndex’ on the collection that is being sorted (has an custom Sort applied).

    Why my problem occured?

    1) I’m changing the value of the object field that is used by SortField (projectInfo.name)
    2) as a consequence - the sort order of sorted collection’s items changes
    3) and then ‘getItemIndex’ cannot return correct value, returns -1 instead.

    Thus, to conclude:

    After changing the value of the object field that is used by SortField, we MUST call:
    projects.refresh();

    to resort the collection to enable ‘getItemIndex’ to return correct value.

Leave a Reply