Easy Tutorial
❮ Event Stopimmediatepropagation Traversing Is ❯

jQuery.grep() Method

jQuery Miscellaneous Methods

Example

Filtering 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>

Definition and Usage

The $.grep() function filters the elements of an array using a specified function and returns the filtered array.

Note: The source array is not affected; the filtering result is only reflected in the returned result array.


Syntax

Parameter Description
array Array type The array to be filtered.
function Function type The specified filter function. The grep() method provides two parameters to the function: one is the current array element being iterated, and the other is the index of the current iterated element in the array.
invert Optional. Boolean type The default value is false, specifying whether to invert the filter result. If the invert parameter is true, the result array will contain all elements for which the function returns false.

More Examples

Filtering the original array

Filtering the original array


jQuery Miscellaneous Methods

❮ Event Stopimmediatepropagation Traversing Is ❯