473,387 Members | 1,897 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Best way to find if item is in array?

What's the best (i.e. fastest) way to find out if an array contains a given
value? Other than looping, the only way I know to do it is to use an
associative array/hash instead....

Is there a better/faster way?

I.e if I have a list of names, what's the best way to find out if the aray
contains "jane"?

--
J.B.Moreno
Aug 31 '05 #1
8 74864
ASM
J. B. Moreno wrote:
What's the best (i.e. fastest) way to find out if an array contains a given
value? Other than looping, the only way I know to do it is to use an
associative array/hash instead....

Is there a better/faster way?

I.e if I have a list of names, what's the best way to find out if the aray
contains "jane"?


don't know if is better ?

alert(myArray.join.indexOf(myValue));
--
Stephane Moriaux et son [moins] vieux Mac
Aug 31 '05 #2
ASM <st*********************@wanadoo.fr.invalid> wrote:
J. B. Moreno wrote:
What's the best (i.e. fastest) way to find out if an array contains a
given value? Other than looping, the only way I know to do it is to
use an associative array/hash instead....

Is there a better/faster way?

I.e if I have a list of names, what's the best way to find out if the
aray contains "jane"?


don't know if is better ?

alert(myArray.join.indexOf(myValue));


I think I understand that, but let me test my understanding:
It joins the array into a string, and then searches inside the string
for the given value? So, if for instance I had myArray = new
Array("frank", "jim'n'jane"); and did
alert(myArray.join.indexOf("jane")); it would find it?

That's not actually a show stopper in this case...but I might have to do
some test to see if it's actually faster.

Anyway, thanks for the alternative

--
J.B.Moreno
Aug 31 '05 #3
"J. B. Moreno" <pl***@newsreaders.com> wrote in message
news:20*******************@newsreader.com...
ASM <st*********************@wanadoo.fr.invalid> wrote:
J. B. Moreno wrote:
What's the best (i.e. fastest) way to find out if an array contains a
given value? Other than looping, the only way I know to do it is to
use an associative array/hash instead....

Is there a better/faster way?

I.e if I have a list of names, what's the best way to find out if the
aray contains "jane"?


don't know if is better ?

alert(myArray.join.indexOf(myValue));


I think I understand that, but let me test my understanding:
It joins the array into a string, and then searches inside the string
for the given value? So, if for instance I had myArray = new
Array("frank", "jim'n'jane"); and did
alert(myArray.join.indexOf("jane")); it would find it?

That's not actually a show stopper in this case...but I might have to do
some test to see if it's actually faster.

Anyway, thanks for the alternative

--
J.B.Moreno


Change
alert(myArray.join.indexOf("jane"));
to
alert(myArray.join().indexOf("jane"));

To ensure that your search string is not embedded try this:

var myJoin = "|" + myArray.join("|") + "|";
alert(myJoin.indexOf("|frank|"));
alert(myJoin.indexOf("|jane|"));

This presumes that "|" is not a character in your array.
Aug 31 '05 #4
ASM
J. B. Moreno wrote:
ASM <st*********************@wanadoo.fr.invalid> wrote:
don't know if is better ?

alert(myArray.join.indexOf(myValue));

error ! have had to read :

alert(myArray.join().indexOf(myValue));
I think I understand that, but let me test my understanding:
It joins the array into a string, and then searches inside the string
for the given value? So, if for instance I had myArray = new
Array("frank", "jim'n'jane"); and did
alert(myArray.join.indexOf("jane")); it would find it?
no

if it finds it returns '1'
if not it returns '-1'

so for true/false :

alert(myArray.join().indexOf(myValue)>=0)

that's to say :

if(myArray.join().indexOf(myValue)>=0) alert('true');
else alert('false');
That's not actually a show stopper in this case...but I might have to do
some test to see if it's actually faster.

a demo ?

<html>
<script type="text/javascript">

tbl = new Array("frank", "jim'n'jane", "moriaux", "toto", "foo");
arr = new Array('potato','salade','pear','orange','apple',ba nana');

alert(tbl.join().indexOf('ri')>=0);
alert(tbl.join().indexOf('st')>=0);
alert('results must have been :\n true\nfalse');

function verif(myArray,myValue) {
var yesno = eval(myArray).join().indexOf(myValue)>=0;
return yesno;
}

document.write('array = "tbl"<br>content = '+tbl.join()+
'<br>array = arr<br>'+arr.join());
</script>
<form onsubmit="alert(verif(I1.value,I2.value));return false;">
<p>Enter array's name : <input name="I1" value="tbl">
Enter search value : <input name="I2" value="">
<hr><p align=center><input type=submit value="verify">
<input type=reset value="reset">
</form>
</html>

--
Stephane Moriaux et son [moins] vieux Mac
Aug 31 '05 #5
"McKirahan" <Ne**@McKirahan.com> wrote in message
news:OI*****************************************@c omcast.com...

<snip>
Change
alert(myArray.join.indexOf("jane"));
to
alert(myArray.join().indexOf("jane"));

To ensure that your search string is not embedded try this:

var myJoin = "|" + myArray.join("|") + "|";
alert(myJoin.indexOf("|frank|"));
alert(myJoin.indexOf("|jane|"));

This presumes that "|" is not a character in your array.


In general, unless your array is very large or you search it a lot, a
client-side loop is just so damn fast why bother playing games?

And if it IS very large or you search it a lot why not set up a hash table?
Then it's just "if ( myHash["Jane"] ) {};" Instant results with no fuss.

Just my opinion of course - which doesn't change the fact that McKirahan's
solution will, indeed, work just fine. ;^)

Jim Davis


Aug 31 '05 #6
ASM
Jim Davis wrote:

And if it IS very large or you search it a lot why not set up a hash table?
Then it's just "if ( myHash["Jane"] ) {};" Instant results with no fuss.

Just my opinion of course - which doesn't change the fact that McKirahan's
solution will, indeed, work just fine. ;^)


tbl = new Array("frank", "jim'n'jane", "moriaux", "toto", "foo");

alert(tbl['toto']);

returns : undefined
--
Stephane Moriaux et son [moins] vieux Mac
Aug 31 '05 #7
ASM wrote on 31 aug 2005 in comp.lang.javascript:
Jim Davis wrote:

And if it IS very large or you search it a lot why not set up a hash
table? Then it's just "if ( myHash["Jane"] ) {};" Instant results
with no fuss.

Just my opinion of course - which doesn't change the fact that
McKirahan's solution will, indeed, work just fine. ;^)


tbl = new Array("frank", "jim'n'jane", "moriaux", "toto", "foo");

alert(tbl['toto']);

returns : undefined


var tbl = {"frank":1, "jim'n'jane":1,
"moriaux":1, "toto":1, "foo":1};

alert(tbl['toto']); // 1

alert(tbl['blahblah']); // undefined

--
Evertjan.
The Netherlands.
(Replace all crosses with dots in my emailaddress)

Aug 31 '05 #8

"ASM" <st*********************@wanadoo.fr.invalid> wrote in message
news:43**********************@news.wanadoo.fr...
Jim Davis wrote:

And if it IS very large or you search it a lot why not set up a hash
table? Then it's just "if ( myHash["Jane"] ) {};" Instant results with
no fuss.

Just my opinion of course - which doesn't change the fact that
McKirahan's solution will, indeed, work just fine. ;^)


tbl = new Array("frank", "jim'n'jane", "moriaux", "toto", "foo");

alert(tbl['toto']);

returns : undefined


I'm sorry... I think you've missed something. This isn't a hash table so it
would, of course, return "undefined".

A "normal" array, as you've built, is indexed by a count (numbers) -
1,2,3,4,5,etc. You can access any element by it's numerical position in the
array (JavaScript also supports numerically indexed arrays where the numbers
are not in order, but leave them out of the discussion for now). You can do
"MyArray[1]", "MyArray[4]", etc. You can loop over the array easily using a
counter loop.

A hash table can be most easily thought (at least by me) of an array indexed
by values (the values can be anything: strings, object references,
whatever). In many languages these values are called "keys" and in
JavaScript they're object properties. You would access values by
"MyHash[MyKeyValue]" (just as you would access any object property using
bracket notation).

So, to demonstrate, try this:

tbl = {"frank": null, "jim'n'jane": null, "moriaux": null, "toto": null,
"foo": null}

This (object literal notation) will create an object where each property is
the "name" and the value is "null". If you need access to array methods in
your hash (most of the time you don't) you might also do this:

tbl = new Array();
tbl["frank"] = null;
tbl["jim'n'jane"] = null;
tbl["moriaux"] = null;
tbl["toto"] = null;
tbl["foo"] = null;

(But, as noted elsewhere, you cannot use any existing array properties -
namely "length" as a key name.)

In either case however try alert(tbl['toto']); again.

This is a very powerful aspect of the language that just doesn't get use "in
the wild".

Jim Davis
Aug 31 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: A frustrated developer | last post by:
I would like to find a specific row on web datagrid, locate its pageindex and itemindex, then highlight to the specific row I found. I know its datakeyfield value, is there anyway we could search...
0
by: panik | last post by:
Hi, I have a custom collection that implements CollectionBase. The collection is called Sensors and contains a list of Sensor objects. There is the usual index using an integer (Sensors). ...
2
by: Angel Monson | last post by:
Is there a way I can find out which item I double-clicked inside a listview? And what about with subitems? And once I get an item number, can I use it to read the item and subitem contents? And if...
1
by: nickyw | last post by:
Hi, Can anyone help, I want to get a reference to a combobox item based on the item's value rather than the text (basically what I am asking is, is there a function like 'FindStringExact' for...
0
by: Benton | last post by:
Hi there, I am using ASP.NET 2.0 and need multiple parameters in Hyperlink column so I add this to my DataGridView: <asp:TemplateField> <ItemTemplate><asp:Hyperlink text="Edit" id="hylEdit"...
4
by: John A. Bailo | last post by:
After upgrading from Outlook 2000 to the 2003 object model, some of my Outlook automation code no longer functions. For example, in 2000, I used to be able to loop through a list of .Items in a...
0
by: Johannes Lochmann | last post by:
Hello list, here is a small code snippet to recursively search a wx.TreeListCtrl for an item with specific pydata. Feel free to comment! def recursiveFindItemByPydata(self, parent,...
2
by: moondaddy | last post by:
I had to repost this because I had to update and change my msdn alias. I will re-ask the question and clarify a few things that were not clear before. This code is all executed on my dev...
1
by: alfiecrosby | last post by:
Hi... this is my first time ti post here... I have a question regarding my PHP study... How do I find out if an array has values posted to each of its elements? I need to know that EVERY...
2
by: scuzz88 | last post by:
i need to make a subroutine that searches an array for an item . If it finds the item it should return the array index of the item, if it does not find then the return value should be -1. if...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.