...

View Full Version : Number of occurences in an array



Basscyst
10-04-2003, 10:22 PM
Is there a method for retrieving the number of times a string is present in an array? I have a one word string per array element. I just need to count how many times each word is present. Any Ideas? Can't seem to figure it out.

Code:

<script language="javascript">
list=new Array();
list[0]=bob;
list[1]=frank;
list[2]=bob;
list[3]=lisa;
list[4]=dan;
list[5]=frank;
</script>

NOTE: The actual array is much larger and is populated from a database so I don't actually know what is in the array until the page loads. I don't think that would matter though.

beetle
10-04-2003, 10:28 PM
Here you go
Array.prototype.countDupes = function( str )
{
var times = -1;
for ( var i = 0; i < this.length; i++ )
{
if ( this[i] == str ) times++;
}
return times;
}

var arr = ['one','two','three','one','four','one','two'];
alert( arr.countDupes( 'one' ) ); // 2
alert( arr.countDupes( 'two' ) ); // 1
alert( arr.countDupes( 'three' ) ); // 0

Basscyst
10-04-2003, 10:31 PM
Much appreciated Beetle. I will try it now.

beetle
10-04-2003, 10:34 PM
No problem. If you want it to return the total number of occurences, and not the actual quantity of duplicates, just change the -1 to a 0, for times



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum