jQuery: The Write Less, Do More JavaScript Library

Utilities/jQuery.grep

From jQuery JavaScript Library

Jump to: navigation, search

« Back to Utilities

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

Filter items out of an array, by using a filter function.
The specified function will be passed two arguments: The current array item and the index of the item in the array. The function must return 'true' to keep the item in the array, false to remove it.
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. Optionally, this argument may be a string rather than a function. If the argument is a string, it is treated as a short "lambda-form" function, with "a" representing the list item and "i" representing the index. For example, "a > 0" may be passed instead of "function(a){ return a > 0; }".
function callback(elementOfArray, indexInArray) {
  var shouldKeepIt;

  this; // unmapped

  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 3. Then it removes all 9s while inverting it.

    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, "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="../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, "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]

Filter an array of numbers to exclude numbers bigger then zero using the third parameter, invert.

$.grep( [0,1,2,3,4,5], "a > 1", true);

[0, 1]

NameType