Search code examples
arraysactionscript-3flash

ActionScript 3.0 - get the count of the same value in an array


working in actionscript3 and have an array problem. I have an array containing numbers, [1,2,3,4,2,1,2,3,4]

how to count number of one value, like the array. count function ["4"] //2

can make an for loop, but like a function for an more easy code.

for(var k:uint = 0; k < array.length; k++)
{
    if (array[k] =="4")
    {
        newarray.push(array[k]);
    }

}
trace(array.length);

thanks for help!


Solution

  • I know it is already answered, but still. If you need just the count, the for..each loop is faster.

    function countItems(value:*, list:Array):int
    {
        var result:int;
    
        for each (var aValue:* in list)
            if (aValue == value)
                result++;
    
        return result;
    }