SitePoint Sponsor |
|
User Tag List
Results 1 to 5 of 5
Thread: Searching Array
-
Sep 21, 2007, 17:06 #1
- Join Date
- May 2007
- Posts
- 242
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Searching Array
Hello. I have a number array with fifty elements. I wish to search the array for the elements whose value is ,say, 5 . Then I will use the element's value and index number in a conditional. In short , how can I search the array for values and retrieve the index number ?
Thanks in advance.
-
Sep 21, 2007, 21:01 #2
- Join Date
- Mar 2005
- Posts
- 141
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Do you mean something like
Code:<script> arr = new Array(); arr[0]="1"; arr[1]="2"; arr[2]="3"; arr[3]="4"; arr[4]="5"; var num=5; function get_index(){ for(var i=0; i<arr.length; i++){ if(arr[i]==num){ var index=i; var index_value=arr[i]; } } } </script>
-
Sep 22, 2007, 01:04 #3
- Join Date
- May 2007
- Posts
- 242
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Thanks for the code @twodogs. Exactly this is the code I seek. But I have to retrieve every index that resides the element whose value is 5. In above code lets assume array[3] and array[4] values are 5. How can I retrieve both index from the loop?
-
Sep 22, 2007, 02:47 #4
- Join Date
- Mar 2005
- Posts
- 141
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
There is probably a better way but this works. Instead of putting the values into a variable put them each into an array.
Code:<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Untitled Document</title> <script> arr = new Array() arr[0]="5" arr[1]="2" arr[2]="5" arr[3]="4" arr[4]="5" index=new Array(); index_value=new Array(); var num=5; function get_index(){ for(var i=0; i<arr.length; i++){ if(arr[i]==num){ index.push(i); index_value.push(arr[i]); } } document.write(index); document.write(index_value); } </script> </head> <body onload="get_index()"> </body> </html>
-
Sep 22, 2007, 14:58 #5
- Join Date
- May 2007
- Posts
- 242
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
That is OK now @twodogs. Thanks.
Bookmarks