LA.NET [EN]

Aug 10

JQuery: utility functions VI – checking if an item is in an array

Posted in JQuery      Comments Off on JQuery: utility functions VI – checking if an item is in an array

In the last post we’ve seen how to get all the items that comply with a specific filter. In this post, we’re going to see how to see if an item is in an array. The easiest way to do that is to use the inArray function. Take a look at the following snippet:

var arr = [0, -2, 4, 6, - 9];
var positives = $.inArray(4,arr);

The inArray method expects two parameters: the item that is going to be checked and the array that is going to be enumerated. Internally, the utility function relies on the the === operator for seeing if any of the array’s items matches the first parameter.

Notice that inArray returns an integer. It will return  non negative integer that represents the position of the passed item. If it doesn’t find a matching item, it will simply return –1. And that’s it. Keep tuned for more on JQuery.