jQuery grep() methodThe 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. SyntaxThe commonly used syntax of grep() method is given as follows. Parameter valuesThis 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. Example1In 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 NowOutput After the execution of the above code, the output will be - After clicking the given button, the output will be - Example2In 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 NowOutput After the execution of the above code, the output will be - On clicking the given button, the output will be - Next TopicjQuery length property |