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.
Page 1 of 2 12 LastLast
Results 1 to 15 of 28

Thread: in_array

  1. #1
    Regular Coder devinemke's Avatar
    Join Date
    Dec 2004
    Location
    NYC
    Posts
    443
    Thanks
    0
    Thanked 12 Times in 11 Posts

    in_array

    this should be simple. is there a javascript equilavent to PHP's in_array() function? i simply want to see in a ceratin element is in an array.

    Code:
    numbers = new Array("one","two","three","four","five");
    // how do i determine id "three" is in this array?
    do i manually have to loop thru and test each element?

  • #2
    Regular Coder
    Join Date
    May 2005
    Location
    Michigan, USA
    Posts
    566
    Thanks
    0
    Thanked 0 Times in 0 Posts
    You miss posted. This has nothing to do with DOM.

    Code:
    Array.prototype.in_array = function ( obj ) {
    	var len = this.length;
    	for ( var x = 0 ; x <= len ; x++ ) {
    		if ( this[x] == obj ) return true;
    	}
    	return false;
    }
    
    numbers = new Array("one","two","three","four","five");
    alert(numbers.in_array("three")) // should evaluate to true

  • #3
    Regular Coder
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    375
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Even simpler:

    Code:
    <script type="text/javascript">
    numbers = new Array("one","two","three","four","five");
    if (numbers.toString().indexOf('three')!==-1)
    alert('Three is in numbers!')
    </script>

  • #4
    Senior Coder
    Join Date
    Feb 2003
    Posts
    1,665
    Thanks
    0
    Thanked 27 Times in 25 Posts
    Quote Originally Posted by jscheuer1
    Even simpler:

    Code:
    <script type="text/javascript">
    numbers = new Array("one","two","three","four","five");
    if (numbers.toString().indexOf('three')!==-1)
    alert('Three is in numbers!')
    </script>

    That's the method I would have gone for.
    Incidentally, is !== -1 any different to != -1 ?
    I ask as I'm more familiar with the latter (!= -1), but the former (!== -1) doesn't throw an error, so I'm wondering…

  • #5
    Banned
    Join Date
    Sep 2003
    Posts
    3,620
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by jscheuer1
    Even simpler:

    Code:
    <script type="text/javascript">
    numbers = new Array("one","two","three","four","five");
    if (numbers.toString().indexOf('three')!==-1)
    alert('Three is in numbers!')
    </script>
    FWIW: The above will allow thre to pass as well as three...

    Code:
    <script type="text/javascript">
     var numbers = new Array("one","two","three","four","five");
      Array.prototype.in_array = function(obj){ 
        return new RegExp('(^|\,)'+obj+'(\,|$)','gi').test(this);
      } 
    
        alert(numbers.in_array("two")) // should evaluate to true 
    
    
    </script>
    .....Willy

  • #6
    Regular Coder
    Join Date
    May 2005
    Location
    Michigan, USA
    Posts
    566
    Thanks
    0
    Thanked 0 Times in 0 Posts
    bool in_array ( mixed needle, array haystack [, bool strict] )

    I did not create the strict, but for the rest of it I coded to the page he provided. You can input objects, strings, numbers, arrays, what ever your heart desires. It will search for it. Not just strings and numbers.
    Last edited by SpirtOfGrandeur; 07-18-2005 at 05:09 PM.

  • #7
    jkd
    jkd is offline
    Senior Coder jkd's Avatar
    Join Date
    May 2002
    Location
    metro DC
    Posts
    3,163
    Thanks
    1
    Thanked 18 Times in 18 Posts
    Using .toString() is bad. For example:

    ["three,four", "five"].toString().indexOf("three") != -1

    BUT, it doesn't contain the value "three".

    Since it seems you're trying to write an equiv. to the PHP version, you may want to also index associative arrays:

    Code:
    Object.prototype.in_array = function(datum, strict) {
        if (strict) function equals(a,b) { return a === b }
        else function equals(a,b) { return a == b }
    
        for (var i in this) {
            if (equals(this[i], datum)) return true;
        }
        return false;
    }
    toString() on an array is still an O(n) operation, so you don't speed up anything at all, and in fact, you might slow it down giving the complexity of string concatenation. Using this version of in_array, you would do:

    ["a", "b", "c"].in_array("b") // true
    {a: 1, b: 2, c: 3 }.in_array(2) // true
    { a: 1, b: 2, c: 3 }.in_array("2", true) // false

  • #8
    Regular Coder
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    375
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Willy, I don't know on what planet 'thre'=='three' but, here on earth and in IE6 , NS7.2 and FF they don't and my script works without mistaking 'thre' for 'three'. It will however mistake 'threee' for 'three', except for this slight mod:
    Code:
    <script type="text/javascript">
    numbers = new Array("one","two","three","four","five");
    if ((','+numbers.toString()+',').indexOf(',three,')!==-1)
    alert('Three is in numbers!')
    </script>
    which will prevent that error.

    Bill, I've just gotten into the habit of always using == in conditionals. I saw somewhere that it is called for (certainly for testing equal) in some cases even when testing for not equal. The distinction seemed hard to remember but, since it also works when the more common != does, I figured - what will it hurt?
    Last edited by jscheuer1; 07-19-2005 at 05:46 AM.

  • #9
    Banned
    Join Date
    Sep 2003
    Posts
    3,620
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by jscheuer1
    Willy, I don't know on what planet 'thre'=='three' but, here on earth and in IE6 , NS7.2 and FF they don't and my script works without mistaking 'thre' for 'three'.
    On this planet... The planet earth... Third rock from the sun...
    Try to get your head out of the clouds and ground yourself...

    Did you try running your script searching for thre??
    Here, run this and let me know what happens...
    Your script throws the alert...
    Thus, thre==three...

    Code:
    <script type="text/javascript">
    numbers = new Array("one","two","three","four","five");
    if (numbers.toString().indexOf('thre')!==-1)
    alert('Three is in numbers!')
    </script>
    .....Willy
    Last edited by Willy Duitt; 07-19-2005 at 08:48 AM.

  • #10
    Banned
    Join Date
    Sep 2003
    Posts
    3,620
    Thanks
    0
    Thanked 0 Times in 0 Posts
    BTW: Your planets must not be properly aligned...
    Your latest revision is even more problematic...

    Code:
    <script type="text/javascript">
    numbers = new Array("one","two","three","four","five");
    if ((','+numbers.toString()+',').indexOf(',three,')!==-1)
    alert('Three is in numbers!')
    </script>
    Your inclusion of the comma's before and after assumes that the string to match will appear in the middle between the beginning and the end of the array... Try searching for one or five...

    Have a nice day;
    .....Willy

  • #11
    Regular Coder
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    375
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Have a closer look, I've added commas before and after the array to string to take care of just such an eventuality.

  • #12
    Banned
    Join Date
    Sep 2003
    Posts
    3,620
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by jscheuer1
    Have a closer look, I've added commas before and after the array to string to take care of just such an eventuality.
    Oh, I see said the blind man...

  • #13
    Regular Coder
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    375
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Yeah, about the thre/three thing. I thought you were putting 'thre' in the array not in the index search. In any case the new method takes care of all eventualities so far mentioned and is still quite simple compared to parsing out the array contents with a 'for i' loop.

  • #14
    Regular Coder
    Join Date
    May 2005
    Location
    Michigan, USA
    Posts
    566
    Thanks
    0
    Thanked 0 Times in 0 Posts
    jscheuer1 yours only does strings or numbers. It does not adhear to jdk or mine which are coded to the in_array() spec.

  • #15
    Banned
    Join Date
    Sep 2003
    Posts
    3,620
    Thanks
    0
    Thanked 0 Times in 0 Posts
    I haven't read the in_array spec but...
    I do not see the need to loop thru the array if, as the O/P originally requested, the intention is to merely check for a match that the search data is present in the array...

    However, if the intention is to match and manipulate the array in some way such as using push, pop, splice or slice... I would agree that looping thru the array would be benificial since it will provide the index to the match's place in the array for further manipulation...

    .....Willy


  •  
    Page 1 of 2 12 LastLast

    Posting Permissions

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