jQuery.grep() method
Example
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 »
Definition and Usage
The $.grep() function filters the elements of an array using a specified function and returns the filtered array.
**Tip:** The source array is not affected; the filtering result is reflected only in the returned result array.
Syntax
$
.grep( array, function [, invert ] )
| Parameters | Description |
|---|---|
| array | Array type: The array to be filtered. |
| function | Function type: The specified filter function. The grep() method provides two arguments to the function: the first is the current array element being iterated, and the second is the index of the current element in the array. |
| invert | Optional. Boolean type: Defaults to false; specifies whether to invert the filtering result. If the invert argument is true, the result array contains all elements for which the function returned false. |
More examples
Filter the original array
Filter out elements with values greater than 0 in the array.
Filter the original array
Filter out elements with values not greater than 0 in the array.
jQuery Miscellaneous Methods