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&lt;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

Custom Search

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

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?

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.

It doesn`t work if array consist of string items, that can contain comma ‘,’ symbol

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;
}

>>> a = new Array(’a', ‘b,c’, ‘d,e,f’);
["a", "b,c", "d,e,f"]

>>> a.toString().search(”c,d”)
4

Thanks to all i didn’t expect so much comments on this topic. I know that this may not work in certain ways on live environment but this is some sort of logical thinking to test the programmer logic.

can i have an example of searching inside of an array?

Leave a comment

(required)

(required)