Description: Finds the elements of an array which satisfy a filter function. The original array is not affected.
The $.grep() method removes items from an array as necessary so that all remaining items pass a provided test. The test is a function that is passed an array item and the index of the item within the array. Only if the test returns true will the item be in the result array.
The filter function will be passed two arguments: the current array item and its index. The filter function must return 'true' to include the item in the result array.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>css demo</title>
<style>
div {
color: blue;
}
p {
color: green;
margin: 0;
}
span {
color: red;
}
</style>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div></div>
<p></p>
<span></span>
<script>
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>
</body>
</html>
$.grep( [ 0, 1, 2 ], function( n, i ) {
return n > 0;
});
$.grep( [ 0, 1, 2 ], function( n, i ) {
return n > 0;
}, true );