Introduction to jquery array filtering method grep of

  • 2020-03-30 03:12:31
  • OfStack

Jquery has a grep() method for filtering array elements, which unfortunately is not found in our API documentation. Look at the official explanation: http://api.jquery.com/jQuery.grep/


Usage of grep() :

Grep (array, the callback, invert)

Array: an array to be filtered;

Callback: processes each element in the array and filters the elements. This function contains two arguments, the first is the value of the current array element and the second is the index value of the current array element. This function should return a Boolean value. Additionally, this function can be set to a string, which when set to a string is treated as a "lambda-form." , where a represents the array element and I represents the element index value. Such as "a > Function (a){return a > 0; }"

Invert: Boolean optional. The default value is false, either true or false. If "invert" is false or set, the function returns the elements in the array that are returned true by the filter function.

After explaining the use of grep(), here's one Example:

var arr=$.grep([0,1,2,3,4,5,6],function(n,i){
 return n>2
});

The above example returns [3,4,5,6], but we give invert a value of true, for example
var arr=$.grep([0,1,2,3,4,5,6],function(n,i){
 return n>2
},ture);

So now it returns [0,1,2], which is the element that was filtered out by the callback function.


Related articles: