Question

Actionscript uses sparse arrays, so I can have an array like this:

var myArray:Array = new Array();
myArray[0] = "foo";
myArray[22] = "bar";

Now myArray.length will give me 23. Is there a way to get the actual number of items in the array without iterating every element?

Was it helpful?

Solution

If you don't want to iterate through the array, you can filter it:

var myArray:Array = new Array();
myArray[0] = "foo";
myArray[22] = "bar";

var numberOfItems:int = myArray.toString().split(',').filter(isItem).length;

function isItem(item:*, index:int, array:Array):Boolean
{
  return item != "";
}

OTHER TIPS

By using for syntax, which will iterate the definded indexes:

public static function definedCount(arr:Array):uint {
    var ctr:uint = 0;
    for(ix:* in arr)
        ctr++;
    return ctr;
}

If you need to frequently check the count of items in a sparse array, you should wrap it an a collection class that independently keeps track of the count of items. Something like:

public class IndexedCollection { 
    private var _arr:Array = [];
    private var _itemCount:uint = 0;

    public function get count():uint {
        return _itemCount;
    }

    public function getItem(index:uint):* { 
        return _arr[index]; 
    }

    public function setItem(index:uint, value:*):void {
        if(_arr[index] === undefined)
            _itemCount++;
        _arr[index] = value; 
    }

    public function delete(index:uint):void { 
        if(_arr[index] === undefined) 
            return;
        delete _arr[index]; 
        _itemCount--;
    }
}

Fastest method should be to always use the inbuilt functions.

    function myFilter(item:*, index:int, array:Array):Boolean{
        if(item)
        {
            return true;
        }else{
            return false;
        }
    }

    var myArray:Array = new Array();
    myArray[0] = "foo";
    myArray[22] = "bar";
    trace(myArray.length) // 23
    var myMyNewArray:Array = myArray.filter(myFilter)
    trace(myMyNewArray .length) // 2
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top