$.grep(array, callback, invert) is jQuery's array filtering utility. It iterates the input array, calls the callback for each element, and returns a new array containing only the elements for which the callback returned true (or a truthy value). It does not modify the original array.
The Invert Argument
The optional third argument flips the logic: pass true to return only elements for which the callback returned false — equivalent to a logical NOT filter. This avoids the need to negate the test inside the callback.
Differences from Array.filter()
ES5's Array.prototype.filter() is available in all modern browsers and is generally preferred in new code. $.grep() is most useful in codebases that target legacy environments or that already use jQuery utilities extensively for consistency.
- Returns a new array — original is not modified
- Callback:
function(element, index)— note reversed argument order vs$.each() - Third argument
trueinverts the filter - Equivalent to modern
array.filter(fn)
Note the callback argument order — element first, index second — is the reverse of $.each() (index first, element second). This inconsistency is a historical quirk of the jQuery API.