jQuery.grep()Method
Examples
Filter the original array
<div></div>
<p></p>
<span></span>
<script>
$(function () {
var arr = [ 1, 9, 3, 8, 6, 1, 5, 9, 4, 7, 3, 8, 6, 9, 1 ];
$( "div" ).text( arr.join( ", " ) );
arr = jQuery.grep(arr, function( n, i ) {
return ( n !== 5 && i > 4 );
});
$( "p" ).text( arr.join( ", " ) );
arr = jQuery.grep(arr, function( a ) {
return a !== 9;
});
$( "span" ).text( arr.join( ", " ) );
})
</script>
Try it Yourself »
Definition and Usage
The $.grep() function uses a specified function to filter elements in an array and returns the filtered array.
Tip:The source array will not be affected; the filtering result is only reflected in the returned result array.
Syntax
$.grep( array, function [, invert ] )
| Parameter | Description |
|---|---|
| array | Array type: the array to be filtered. |
| function | Function type: the specified filter function. The grep() method provides two parameters for the function: the first is the array element currently being iterated, and the second is the index of the current element in the array. |
| invert | Optional. Boolean type: the default value is false, specifying whether to invert the filtering result. If the invert parameter is true, the result array will contain all elements for which the function returns false. |
More Examples
Filter the original array
Filter out elements in the array with values greater than 0.
Filter the original array
Filter out elements in the array with values not greater than 0.
Other Extensions
jQuery Miscellaneous Methods