Tuesday, August 14, 2012

jQuery Function of the Week: grep

This week's jQuery function of the week is grep.  According to the jQuery docs grep:
Finds the elements of an array which satisfy a filter function. The original array is not affected.
There is only a single signature for the grep function: $.grep(array, function(element, index) [,invert]). The function being passed in should return a truthy value or a falsy value based on the input argument.  If the invert parameter is left out, or is false then the grep function will return a new array with all the items that the satisfy the truth test function that was passed in.  If invert is set to true, grep will return a new array with all the items that do not satisfy the truth test function.

Lets take a look at looping through an array of text and removing the word "the":

JS Bin demo

Now lets take a look at the same code, but with the invert parameter set to true:

JS Bin demo

You'll see that only the word "the" is returned.

Check out the all of the jQuery function's of the week.
Fork me on GitHub