Hi,
I have an array with duplicate values (strings) in it.
I would like to have a function that i can call with the string-parameter and returns how many times this string is in the array.
thank you!
Hi,
I have an array with duplicate values (strings) in it.
I would like to have a function that i can call with the string-parameter and returns how many times this string is in the array.
thank you!
function arrayCount(arrayName:Array, arrayElement:String) {
var n:Number = 0;
var i:Number = arrayName.length;
while (i--) {
if (arrayName* == arrayElement) {
n++;
}
}
return n;
}
myArray = ["dog", "cat", "mouse", "dog", "cat", "cat", "dog", "mouse", "cat"];
trace(arrayCount(myArray, "dog"));
trace(arrayCount(myArray, "cat"));
trace(arrayCount(myArray, "mouse"));
Thank you, it worked!
I think you could do it faster witout using a loop, jsut take the length of the array with the items removed, from the actual length
Just because I can, here’s another way to do it.
function equals(element:*, index:int, arr:Array):Boolean{
return element == this;
}
var myArray:Array = ["dog", "cat", "mouse", "dog", "cat", "cat", "dog", "mouse", "cat"];
trace(myArray.filter(equals, "dog").length);
trace(myArray.filter(equals, "cat").length);
trace(myArray.filter(equals, "mouse").length);
The filter method of the Array class runs a given function on each array item that returns a boolean. filter then returns an array of all the items that the function returned true on. The second parameter of the filter method maps to the functions this parameter, so that is how I check the element against what is given.
I’d like to see that…of course, without looping through the array how would you know which items to remove?
Again, I’d like to see this working in ActionScript 1.0 or 2.0…neither of which have an Array.filter() method
Oh, duh, I’m in the wrong forum.
look up the split() and join() functions
:: Copyright KIRUPA 2024 //--