inArray in JavaScript


First of I would like to say that JavaScript doesn’t provide inArray or in_array method to check if a value exists in an array like php do PHP: in_array😦

Well we have some good options instead😀

But before using some custom inArray method, you better know that if you are a jQuery freak then this post is not for you because jQuery have a nice utility jQuery.inArray() – jQuery API

Yeah! we are talking about raw and plain JavaScript implementation of in_array in JavaScript.

For this we are going to add a inArray prototype method into Array class of JavaScript using simple linear search inside that method like below:

Array.prototype.inArray = function (value)
{
 // Returns true if the passed value is found in the
 // array. Returns false if it is not.
 var i;
 for (i=0; i < this.length; i++)
 {
 if (this[i] == value)
 {
 return true;
 }
 }
 return false;
};

Awesome! right😀

Now we will use it in terms of JavaScript feature as we have already added inArray method as Array class method

var testArr= ["Shrek","Feona","Donkey"];
//use of inArray
if(testArr.inArray("Donkey"))
   document.write('Are we there yet!!!!');
else
   document.write('Thank God!!!');

Here with our inArray prototype method implementation we are able to access inArray using DOT(.) with the given array object where most of the in_array methods takes main array as haystack and a value as needle such as in_array(search_value,array) .

This function should work fairly well on relatively small lists of items. For a larger array, a binary search function may be more appropriate.

In this way you may implement some more handy javascript prototype method.

Cheers!🙂

9 thoughts on “inArray in JavaScript

  1. Not a fan of jQuery’s implementation because it doesn’t check to see if the actual value matches. If you wanted to check for exact values

    “this[i] == value” should be “this[i] === value” instead.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s