jQuery.grep()

Finds the elements of an array which satisfy a filter function. The original array is not affected.

jQuery.grep(array, function(elementOfArrayObject, indexInArrayInteger), invert)🡢 Array

array ArrayLikeObjectThe array-like object to search through.
function(elementOfArrayObject, indexInArrayInteger) FunctionThe function to process each item against. The first argument to the function is the item, and the second argument is the index. The function should return a Boolean value. this will be the global window object.
invert BooleanIf "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.

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.

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

JS
<div></div>
<p></p>
<span></span>
CSS
div {
  color: blue;
}
p {
  color: green;
  margin: 0;
}
span {
  color: red;
}
HTML
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(", "));
DEMO

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

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

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

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

Looking for a Web Developer?

👋

Hi! I'm Basti, author of this site. If you are looking for a web developer with 15+ years of experience, holla at me!

Be it the good 'ol jQuery, vanilla JS or modern frameworks like Vue and Svelte, front- or backend, I can help you.

Just write me at jobs@jqapi.com :)