Find Array value

In Category Useful Functions
Article published 28/02/2011 12:09:33pm
Find Array valueFind Array value

A simple function to easily find the key for an Array value in Javascript, or return -1 if the value has not been found in the target Array. The function extends the existing Array object so can easily be called on any Array.

Sometimes in Javascript it becomes necessary to search for a given value within an Array. We can do this by extending the Array object in Javascript with a prototype function. The function works in the following way:
  1. The function takes the Array value to search for as the arguament
  2. All elements in the Array are looped through until the end is reached, or a match is found
  3. If a match is found the key is returned
  4. If no match is found once the whole array has been looped through, -1 (minus one) is returned
Array.prototype.find = function(str) {
  for(x in this) {
    if(this[x]==str) { return x; }
  return -1;