JavaScript Tutorial - Search inside Array without Looping
While doing programming we often want to search for specific content inside the array and in general programmers would perform a looping operation on the array to search for the specific content. But below is the small code snippet written in JavaScript that can search for content in array without using Loops.
<script type="text/javascript"> var i=1000; var arr_obj = new Array(); for(i=0;i<1000;i++) { arr_obj[i] = "Hello World!!!" + Number(i+1); //Creating an array having 1000 element } var arr2str = arr_obj.toString(); //Converting the String content to String document.write(arr2str.search("Hello World!!!345")); //Search for the Content in the arr2str </script>
Output: Hello World!!!345
Explanation:
It a two step process to search for the content in an array
Convert the whole array content to String and is stored in arr2str
Search for specific word in arr2str by using .search method of String Object
Similar Posts
Did you enjoy this post? Why not leave a comment below and continue the conversation, or subscribe to my feed and get articles like this delivered automatically to your feed reader.
Comments
An interesting idea - but for what purpose? I’m not sure why you would want to avoid an explicit loop, and this is quite inefficient as it results in two loops - one for the toString() call and one for the search() call.
A benchmark on 100000 elements searching for element #12345 consistently shows that the toString()/search() method requires approximately 10x the amount of time to execute.
What are you trying to do ?
Just to know if the array contains a value or the index of the value in the array ?
The first solution, I think.
I sometime use only a string in my apps and no array at all :
converting array to string is time consumming.
var allowedCountries = “/fr/en/de/es/”;
function isAllowed(country) {
return allowedCountries.indexOf(”/”+ country +”/”) != -1;
}


How do you think the search() method works? What does it need to do in order to find that piece of string you just supplied it as parameter? I’m pretty sure it loops through the humongous string you created. At least I’d very surprise if it did it any other way.
Have you tested which is faster? An array search or the method you propose?