Go Back   CodingForums.com > :: Client side development > JavaScript programming

Before you post, read our: Rules & Posting Guidelines

Closed Thread
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 07-18-2005, 03:39 PM   PM User | #1
devinemke
Regular Coder

 
devinemke's Avatar
 
Join Date: Dec 2004
Location: NYC
Posts: 443
Thanks: 0
Thanked 12 Times in 11 Posts
devinemke is an unknown quantity at this point
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?
devinemke is offline  
Old 07-18-2005, 04:05 PM   PM User | #2
SpirtOfGrandeur
Regular Coder

 
Join Date: May 2005
Location: Michigan, USA
Posts: 566
Thanks: 0
Thanked 0 Times in 0 Posts
SpirtOfGrandeur is an unknown quantity at this point
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
SpirtOfGrandeur is offline  
Old 07-18-2005, 04:26 PM   PM User | #3
jscheuer1
Regular Coder

 
Join Date: Mar 2005
Location: SE PA USA
Posts: 373
Thanks: 0
Thanked 0 Times in 0 Posts
jscheuer1 is an unknown quantity at this point
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>
jscheuer1 is offline  
Old 07-18-2005, 04:43 PM   PM User | #4
Bill Posters
Senior Coder

 
Join Date: Feb 2003
Posts: 1,665
Thanks: 0
Thanked 27 Times in 25 Posts
Bill Posters will become famous soon enough
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…
Bill Posters is offline  
Old 07-18-2005, 05:01 PM   PM User | #5
Willy Duitt
Banned

 
Join Date: Sep 2003
Posts: 3,620
Thanks: 0
Thanked 0 Times in 0 Posts
Willy Duitt is an unknown quantity at this point
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
Willy Duitt is offline  
Old 07-18-2005, 05:06 PM   PM User | #6
SpirtOfGrandeur
Regular Coder

 
Join Date: May 2005
Location: Michigan, USA
Posts: 566
Thanks: 0
Thanked 0 Times in 0 Posts
SpirtOfGrandeur is an unknown quantity at this point
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..
SpirtOfGrandeur is offline  
Old 07-18-2005, 05:50 PM   PM User | #7
jkd
Senior Coder

 
jkd's Avatar
 
Join Date: May 2002
Location: metro DC
Posts: 3,163
Thanks: 1
Thanked 18 Times in 18 Posts
jkd will become famous soon enough
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
__________________
jasonkarldavis.com
jkd is offline  
Old 07-19-2005, 05:21 AM   PM User | #8
jscheuer1
Regular Coder

 
Join Date: Mar 2005
Location: SE PA USA
Posts: 373
Thanks: 0
Thanked 0 Times in 0 Posts
jscheuer1 is an unknown quantity at this point
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..
jscheuer1 is offline  
Old 07-19-2005, 08:31 AM   PM User | #9
Willy Duitt
Banned

 
Join Date: Sep 2003
Posts: 3,620
Thanks: 0
Thanked 0 Times in 0 Posts
Willy Duitt is an unknown quantity at this point
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..
Willy Duitt is offline  
Old 07-19-2005, 08:39 AM   PM User | #10
Willy Duitt
Banned

 
Join Date: Sep 2003
Posts: 3,620
Thanks: 0
Thanked 0 Times in 0 Posts
Willy Duitt is an unknown quantity at this point
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
Willy Duitt is offline  
Old 07-19-2005, 09:18 AM   PM User | #11
jscheuer1
Regular Coder

 
Join Date: Mar 2005
Location: SE PA USA
Posts: 373
Thanks: 0
Thanked 0 Times in 0 Posts
jscheuer1 is an unknown quantity at this point
Have a closer look, I've added commas before and after the array to string to take care of just such an eventuality.
jscheuer1 is offline  
Old 07-19-2005, 09:45 AM   PM User | #12
Willy Duitt
Banned

 
Join Date: Sep 2003
Posts: 3,620
Thanks: 0
Thanked 0 Times in 0 Posts
Willy Duitt is an unknown quantity at this point
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...
Willy Duitt is offline  
Old 07-19-2005, 10:11 AM   PM User | #13
jscheuer1
Regular Coder

 
Join Date: Mar 2005
Location: SE PA USA
Posts: 373
Thanks: 0
Thanked 0 Times in 0 Posts
jscheuer1 is an unknown quantity at this point
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.
jscheuer1 is offline  
Old 07-19-2005, 12:24 PM   PM User | #14
SpirtOfGrandeur
Regular Coder

 
Join Date: May 2005
Location: Michigan, USA
Posts: 566
Thanks: 0
Thanked 0 Times in 0 Posts
SpirtOfGrandeur is an unknown quantity at this point
jscheuer1 yours only does strings or numbers. It does not adhear to jdk or mine which are coded to the in_array() spec.
SpirtOfGrandeur is offline  
Old 07-19-2005, 01:03 PM   PM User | #15
Willy Duitt
Banned

 
Join Date: Sep 2003
Posts: 3,620
Thanks: 0
Thanked 0 Times in 0 Posts
Willy Duitt is an unknown quantity at this point
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
Willy Duitt is offline  
Closed Thread

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 11:38 PM.


Advertisement
Log in to turn off these ads.