arraysapache-flexactionscript-3slicexmllist

Slice XMLList instead of Array


How would I get a range of items from my xmllist similar to the slice method for an array?

slice(startIndex,endIndex);

I am trying something like this:

            var tempXMLList:XMLList = new XMLList();

            for( var i:int = startIndex; i <= endIndex; i++){
                tempXMLList += originalList[i];
            }

But I am getting an error that it can't convert originalList[i]

--- Update ---

I used Timofei's function and it worked perfectly.

private function SliceXMLList(xmllist : XMLList, startIndex : int, endIndex : int) : XMLList
{
    return xmllist.(childIndex() >= startIndex && childIndex() <= endIndex);
}

However, when I use an xmllist that was already been filtered, it breaks.

filteredData = filteredData.(team == "Ari");

trace("filteredData.length(): " + filteredData.length().toString());
pData = SliceXMLList(filteredData, startIndex, endIndex);
trace("start: " + startIndex.toString() + " end: " + endIndex.toString());
trace("pdata length: " + pData.length().toString());

output

filteredData.length(): 55
start: 0 end: 55
pdata length: 5

Solution

  • Use e4x.

    private function SliceXMLList(xmllist : XMLList, startIndex : int, endIndex : int) : XMLList
    {
        return xmllist.(childIndex() >= startIndex && childIndex() <= endIndex);
    }
    

    Update:

    There's a problem, if you're going to use this function after some e4x-sorting, 'cause the childIndex() function returns the old values of the nodes' indexes and it cannot be changed. So, I have another idea:

    private function SliceXMLList(xmllist : XMLList, startIndex : int, endIndex : int) : XMLList
    {
        for (var i : int = 0; i < xmllist.length(); i++)
            xmllist[i].@realIndex = i;
        xmllist =  xmllist.(@realIndex >= startIndex && @realIndex <= endIndex);
        for (i = 0; i < xmllist.length(); i++)
            delete xmllist[i].@realIndex;
        return xmllist;
    }
    

    or just

    private function SliceXMLList(xmllist : XMLList, startIndex : int, endIndex : int) : XMLList
    {
        var newXMLList : XMLList = new XMLList();
        var currIndex : int = 0;
        for (var i : int = startIndex; i <= endIndex; i++)
            newXMLList[currIndex++] = xmllist[i];
        return newXMLList;
    }
    

    This is the best variant, i think. Of course one-line e4x statement is much more elegant, but unfortunately it's not reusable.