Find matching elements given in an array
You can simply do this:
private function getCount(fruitArray:Array, fruitName:String):int {
var count:int=0;
for (var i:int=0; i<fruitArray.length; i++) {
if(fruitArray[i].toLowerCase()==fruitName.toLowerCase()) {
count++;
}
}
return count;
}
var fruit:Array = ["apples", "oranges", "grapes", "oranges", "apples", "grapes"];
var appleCount=getCount(fruit, "apples"); //returns 2
var grapeCount=getCount(fruit, "grapes"); //returns 2
var orangeCount=getCount(fruit, "oranges"); //returns 2
source to share
Depending on the number of elements in the array and how often you want to search for different elements, it can be very costly for the loop to loop through the entire array every time you want to count things (what if you did what the other two suggest answer). You might want to have a count function that iterates through the array only once and returns a list of counters instead of a single number:
function countItems( arr:Array ) : Object {
var counts : Object = {};
for each ( var item : String in arr ) {
if (counts.hasOwnProperty(item)) counts[item]++;
else counts[item] = 1;
}
return counts;
}
var fruit:Array = ["apples", "oranges", "grapes", "oranges", "apples", "grapes"];
var counts : Object = countItems(fruit);
trace (counts["apples"]); // => 2
trace (counts["oranges"]); // => 2
trace (counts["grapes"]); // => 2
source to share
function countOccurrences( haystack, needle ){
var index : int = -1;
var counter : int = -1;
do{
counter++;
index = haystack.indexOf( needle, index + 1 );
}while( index >= 0 );
return counter;
}
var fruit:Array = ["apples", "oranges", "grapes", "oranges", "apples", "grapes"];
trace( countOccurrences( fruit, "apples" ) ); //outputs '2'
source to share
var stringToSearch:String = "apples";
var pattern:RegExp = new RegExp(/\b\b/.source+stringToSearch, "g");
var matches:Array = fruit.toString().match(pattern);
//
trace(matches.length);
Disclaimer: Don't use this if you have many elements in your array (e.g. fruit.length> 1000): it's compact, but it might be slower than any other solution posted here. Another thing to note is that here I am assuming your "matched items" are "strings".
source to share
Try something like
private function makeFilter(filterValue:String):Function {
var fn:Function = function (obj:Object, index:int=0, arr:Array=[]):Boolean {
if (String(obj)==filterValue) {
return true;
}
return false;
}
return fn;
}
//somewhere else:
var filterFunction:Function = makeFilter('apples');
var appleCount:int = fruit.filter(filterFunction).length;
FYI, more about this approach: http://www.gasi.ch/blog/functional-actionscript-1/
source to share