Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    Smokes a Lot
    Join Date
    Jul 2003
    Location
    CA, USA
    Posts
    1,594
    Thanks
    5
    Thanked 20 Times in 20 Posts

    Number of occurences in an array

    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.
    Last edited by Basscyst; 10-04-2003 at 10:26 PM.

  • #2
    Senior Coder
    Join Date
    Aug 2002
    Posts
    3,467
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Here you go
    Code:
    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
    My Site | fValidate | My Brainbench | MSDN | Gecko | xBrowser DOM | PHP | Ars | PVP
    “Minds are like parachutes. They don't work unless they are open”
    “Maturity is simply knowing when to not be immature”

  • #3
    Smokes a Lot
    Join Date
    Jul 2003
    Location
    CA, USA
    Posts
    1,594
    Thanks
    5
    Thanked 20 Times in 20 Posts
    Much appreciated Beetle. I will try it now.

  • #4
    Senior Coder
    Join Date
    Aug 2002
    Posts
    3,467
    Thanks
    0
    Thanked 0 Times in 0 Posts
    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
    My Site | fValidate | My Brainbench | MSDN | Gecko | xBrowser DOM | PHP | Ars | PVP
    “Minds are like parachutes. They don't work unless they are open”
    “Maturity is simply knowing when to not be immature”


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •