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 3 of 3
  1. #1
    New to the CF scene
    Join Date
    Aug 2012
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Getting the index from a two dimensional array.

    Hi, I have stumbled on the following problem:

    How do I retrieve the index from a two dimensional array:

    For example the code is:

    a=new Array(5);
    a[0]=new Array('a','b','c','d','e');

    But how would I retrieve the index of 'c' from a[0]

    Thanks in advance,
    Andy.

  • #2
    Senior Coder
    Join Date
    Sep 2010
    Posts
    2,451
    Thanks
    17
    Thanked 275 Times in 275 Posts
    Code:
    for ( i = 0 ; i < a[0].length ; i++)
    {
    if ( a[0][i] == c ) alert(i);
    }

  • #3
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    27,543
    Thanks
    80
    Thanked 4,617 Times in 4,581 Posts
    In most browsers, you could also use indexOf().

    Thus:
    Code:
    var a = [ ];
    a[0]=new Array('a','b','c','d','e');
    document.write( a[0].indexOf('c') );
    And if a browser doesn't support Array.indexOf( ) you can easily add it:

    Code:
    if (Array.prototype.indexOf == null ) 
    {
        Array.prototype.indexOf = 
            function( target, first )
            {
                if ( first == null ) { first = 0; }
                for ( var i = first; i < this.length;  ++i )
                {
                    if ( this[i] === target ) { return i; }
                }
                return -1;
            };
    }
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.


  •  

    Posting Permissions

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