JavaScript inArray()

Lukas on Jan 26th 2008

Everybody who uses JavaScript every now and then is bound to sooner or later notice the absence of an inArray function, i.e. a function that allows you to check if a certain value is an element of an array.

When I went looking for a custom function to search arrays for me I found many approaches to solve the problem. Here is my personal flavour of the inArray function, composed out of the ones I found online:

The Function

1
2
3
4
5
6
7
8
9
10
11
Array.prototype.inArray = function ( search_phrase )
{
  for( var i = 0; i < this.length; i++ )
  {
    if( search_phrase == this[i] )
    {
      return i;
    }
  }
  return false;
}

Example

12
13
14
myArray = new Array('a', 'b', 'c');alert(myArray.inArray('a'));  //outputs 0
alert(myArray.inArray('c'));  //outputs 2
alert(myArray.inArray('d'));  //outputs false

As you can see the function can be appended to the array when needed, just as the regular JavaScript functions for arrays.
When searching for a value the function will return the index of the array element on success, or “false” if it cannot be found.

A Note of Caution:

When comparing with this function you should always use the === operator rather than ==. This is necessary because in JavaScript 0 evaluates to false. Since == compares the value the comparison 0 == false yields true. === forces a comparison of type in addition to a comparison of value, causing the comparison 0 ===false to yield false as 0 is not of type boolean, whereas false is.

Filed in JavaScript | One response so far

One Response to “JavaScript inArray()”

  1. Andrew Jan 29th 2009 at 10:09 am 1

    Thanks needed that

Comments RSS

Leave a Reply