Примеры для jQuery.grep()


Filters the original array of numbers leaving that are not 5 and have an index greater than 4. Then it removes all 9s.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery.grep demo</title>
<style>
div {
color: blue;
}
p {
color: green;
margin: 0;
}
span {
color: red;
}
</style>
<script src="https://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>

Демонстрация:

Filter an array of numbers to include only numbers bigger then zero.

1
2
3
$.grep( [ 0, 1, 2 ], function( n, i ) {
return n > 0;
});

Result:

1
[ 1, 2 ]

Filter an array of numbers to include numbers that are not bigger than zero.

1
2
3
$.grep( [ 0, 1, 2 ], function( n, i ) {
return n > 0;
}, true );

Result:

1
[ 0 ]