ドキュメント

Utilities/jQuery.grep

From jQuery JavaScript Library

Jump to: navigation, search

« Back to Utilities

jQuery.grep( array, callback, [invert] )

Finds the elements of an array which satisfy a filter function. The original array is not affected.
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.
Arguments:

arrayArray
The Array to find items in.
callbackFunction
The function to process each item against. The first argument to the function is the list item, and the second argument is the list index. The function should return a Boolean value. The "lambda-form" function feature was removed in jQuery 1.2.3 to help compatibility with other frameworks.
function callback(elementOfArray, indexInArray) {
  var shouldKeepIt;

  this; // == window

  return shouldKeepIt;
}
invert (Optional)Boolean
If "invert" is false, or not provided, then the function returns an array consisting of all elements for which "callback" returns true. If "invert" is true, then the function returns an array consisting of all elements for which "callback" returns false.
Examples:

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

    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(", "));

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  
  <script>
  $(document).ready(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>
  <style>
  div { color:blue; }
  p { color:green; margin:0; }
  span { color:red; }
  </style>
</head>
<body>
  <div></div>
  <p></p>
  <span></span>
  
</body>
</html>

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

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

[1, 2]

NameType