Thursday, May 16, 2013

Match an element against an array in Javascript

There are times when you need to check whether an element is inside an array. You might want to loop thorough the whole array and check one-by-one whether the element belongs to an array or not:
var element = "one";
var array = ["one", "two", "three"];

for (var i= 0; i < array.length; i++)
{
   if (element === array[i])
   {
      alert("element exists in array");
   }
}
This approach is not optimized. First, it will produce additional lines of unnecessary code and therefore makes the code look ugly. Second, looping through element of an array is costly, especially when the array has two many elements. A more optimized way of handling this case is with use of Regular Expressions. Without further a due, let us look at the code:
if ((new RegExp('\\b' + array.join('\\b|\\b') + '\\b') ).test(element))
{
   alert("element exists in array");
}
In this approach, we create a new regular expression by joining elements of array into an string and match it against the element with test() method. Just to remark, \b matches the empty string at the beginning or end of a word.

1 comment:

  1. array.join will internally loop through all elements in the array to produce the string on which you are performing the regex.

    At least doing a search through the array has the option of exiting as soon as the element is found.

    ReplyDelete