JQuery: utility functions V – finding elements in an array
Today we’re going to talk about the grep utility function. You can use the grep function to get the elements of the array that match a specific custom filter. The grep function expects three parameters. The first two are mandatory: an array that is going to be enumerated and a callback function which is responsible for checking which items of the array comply with the custom filter (the function will be called for each item of the array and should return a boolean which indicates if the current item is compatible with the desired filter). Finally, you can also pass grep a third parameter for inverting the result of the filtering (more on this in the next paragraphs).
Lets start with a basic example: get all the positive numbers from an array. Here’s some simple code that performs this:
var arr = [0, -2, 4, 6, - 9];
var positives = $.grep(arr,
function(item) {
return item > 0;
});
alert(positives);
The function receives two parameters: a reference to the current value and the index of that value in the array. Since I was only interested in the value, I opted for declaring only one parameter in the anonymous function that filters the arr array.
As I mentioned before, the grep function has a third optional parameter: it’s called invert and you’re supposed to pass a boolean (that is, when you use it). If you pass true, you’ll be inverting your filter, ie, you’ll get the items which don’t comply to the filter you’ve defined in the anonymous function. So, if we wanted to get all the negative values, we could rewrite the anonymous function’s filter or we could pass true to the third parameter of grep, as you can see in the next snippet:
var arr = [0, -2, 4, 6, - 9];
var positives = $.grep(arr,
function(item) {
return item > 0;
},
true);
alert(positives);
And I guess there’s not much to say about grep. Keep tuned for more on
JQuery.