Search code examples
arraysactionscript-3countsparse-array

How can I get the number of elements in a sparse array in Actionscript?


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?


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 != "";
    }