jQuery grep() Method

Last Updated:

jQuery grep() Method

The jQuery grep() method finds the elements of an array which satisfy a filter function.

Note: This method will not affect the original array.

Filter without Invert

In the following example, we will filter all the elements in an array (arr) which are divisible by 3.

Example

HTML Editor
<!DOCTYPE html> <html lang="en-US"> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <h1>jQuery grep() Method</h1> <p>Click on the button and check your console.</p> <button>Click Me</button> <script> $(document).ready(function(){ $("button").click(function(){ var arr = [1, 2, 3, 4, 5, 6]; arr = $.grep( arr, function(n, i) { return n % 3 == 0; }, false); console.log(arr); }); }); </script> </body> </html>

Syntax

$.grep(arr, callback, invert);

Parameter Values

Value Type Explanation
arr Required Specifies an array-like object to search through.
callback Required Specifies a function to process each item against.
invert Optional Specifies whether to invert the result or not.
Possible values are
  • false - Do Not Invert
  • true - Invert
Default value of invert is false.

Browser Support

Devicedesktopmobile
Browsergoogle chromesafarifirefoxinternet Exploreredgeoperagoogle chromesafarifirefoxedgeoperaandroid webviewsamsung internet
grep()YesYesYesYesYesYesYesYesYesYesYesYesYes

Filter with Invert

In the following example, we will filter all the elements in an array (arr) which are NOT divisible by 3.

Example

HTML Editor
<!DOCTYPE html> <html lang="en-US"> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <h1>jQuery grep() Method</h1> <p>Click on the button and check your console.</p> <button>Click Me</button> <script> $(document).ready(function(){ $("button").click(function(){ var arr = [1, 2, 3, 4, 5, 6]; arr = $.grep( arr, function(n, i) { return n % 3 == 0; }, true); console.log(arr); }); }); </script> </body> </html>

Share this Page

Meet the Author