jQuery grep() Method
You are Here:
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
|
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>
Reminder
Hi Developers, we almost covered 99.5% of jQuery Tutorials with examples for quick and easy learning.
We are working to cover every Single Concept in jQuery.
Please do google search for:
Join Our Channel
Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.
This channel is primarily useful for Full Stack Web Developer.