Javatpoint Logo
Javatpoint Logo

jQuery grep() method

The grep() method in jQuery finds the array elements that satisfy the given filter function. It does not affect the original array. This method returns the filtered array, i.e., the elements that satisfy the given filter function.

Syntax

The commonly used syntax of grep() method is given as follows.

Parameter values

This method includes some parameters that are defined as follows.

array: It is the mandatory parameter. It specifies an array-like object to search.

function(element, index): This specifies a function which is used as a filter function. It accepts two arguments named as element and index in which the first argument holds the array element, and the second argument holds the index of the corresponding element. It returns a Boolean value, either true or false. It is also a mandatory parameter. This function processes each array element. If the element passes the condition, only then it will be included in the result.

invert: It is an optional parameter. It accepts Boolean values. Its default value is false. If it is specified to false or not passed, the grep() function returns the array elements for which the filter function returns true. If this parameter is specified to true, the grep() function returns the array elements for which the filter function returns false.

Now, let's see some illustrations of using the grep() method.

Example1

In this example, there is an array named as arr with some items. We are applying the grep() method on this array, and not specifying its optional invert parameter. So, the method returns the array elements that are completely divisible by 2 with an index greater than or equal to 2.

Test it Now

Output

After the execution of the above code, the output will be -

jQuery grep() method

After clicking the given button, the output will be -

jQuery grep() method

Example2

In this example, we are using the invert parameter and set it to true. Here, there is an array named as arr with some items. If we don't set the invert parameter to true, the function returns the array elements not equal to 60. But as we are using the invert parameter and set it to true, so the function returns the array elements with value 60.

In the output, we can see that the grep() method returns the array elements for which the specified filter function returns false.

Test it Now

Output

After the execution of the above code, the output will be -

jQuery grep() method

On clicking the given button, the output will be -

jQuery grep() method





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA