jQuery grep() Method

Beginner
6 min read
Updated: Oct 2026
4 examples
Live preview

What Is grep()?

jQuery.grep(array, function[, invert]) (alias $.grep) keeps items that pass a boolean test (since jQuery 1.0). Optional invert flips the test — keep where the callback returns false.

Remember
$.grep(array, function(element, index) {
  return true;   // keep this element
})

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

$.grep([0, 1, 2], function (n) { return n > 0; }, true)
// → [0]   (invert)
NeedUse
Keep items that pass a test$.grep(arr, fn)
Keep items that fail a test$.grep(arr, fn, true)
Transform values$.map(arr, fn)
Native array filterarr.filter(fn)

How to Use grep()

Pass an array-like list, a boolean callback, and optionally invert.

  1. Start with an array (or array-like object with length).
  2. Write a function that receives (element, index) and returns true or false.
  3. Call $.grep(array, fn) to keep passing items.
  4. Pass true as the third argument to keep failing items instead.
PieceRequired?Role
arrayYesArray-like object to search
functionYesBoolean test: (element, index) → Boolean
invertNoIf true, keep where callback is false
Return—New Array (source unchanged)

Pseudocode

Pseudocode
function grep(array, fn, invert):
    result = []
    for i from 0 to array.length - 1:
        pass = fn(array[i], i)   // must be boolean-ish
        if invert:
            keep = not pass
        else:
            keep = pass
        if keep:
            result.push(array[i])
    return result   // new array; original untouched

Cheat Sheet

Keep these facts handy while filtering with jQuery.

TopicDetail
SyntaxjQuery.grep(array, function[, invert])
SincejQuery 1.0
Callback(element, index) → Boolean
thisGlobal window (not the element)
Mutates?No — returns a new array
Inverttrue → keep failed tests
vs map$.map transforms; $.grep selects

Live Preview

Filter [0, 1, 2, 5, 9] with a few common $.grep rules.

Browser demo of $.grep() — same idea as the examples below.

Result
arr = [0, 1, 2, 5, 9]
rule = n > 0
→ [1, 2, 5, 9]

jQuery Examples

Short, copy-ready snippets. Open DevTools Console, or use Try It Yourself for a live editor.

Example 1 — Keep Numbers Greater Than Zero

Official simple filter: drop zeros and negatives.

jQuery
var result = $.grep([0, 1, 2], function (n) {
  return n > 0;
});

console.log(result);  // [1, 2]
Try It Yourself

How It Works

  1. Source. Start with [0, 1, 2].
  2. Test. Callback returns true only when n > 0.
  3. Keep. 1 and 2 pass; 0 fails.
  4. Result. A new array [1, 2] — the original list is unchanged.

Example 2 — Invert the Test

Same callback, opposite keep rule with invert: true.

jQuery
var result = $.grep([0, 1, 2], function (n) {
  return n > 0;
}, true);

console.log(result);  // [0]
Try It Yourself

How It Works

  1. Same test. Callback still asks n > 0.
  2. Third argument. true means keep where the callback is false.
  3. Keep failures. Only 0 fails n > 0.
  4. Result. [0] — handy when the reject rule is easier to write.

Example 3 — Filter with Value and Index

Use both callback arguments, like the official demo.

jQuery
var arr = [1, 9, 3, 8, 6, 1, 5, 9, 4, 7];

var result = $.grep(arr, function (n, i) {
  return n !== 5 && i > 4;
});

console.log(result);  // [1, 9, 4, 7]
Try It Yourself

How It Works

  1. Two args. n is the value; i is its index.
  2. Index rule. i > 4 drops the first five slots.
  3. Value rule. n !== 5 drops the 5 at index 6.
  4. Survivors. From the tail: 1, 9, 4, 7.

Example 4 — Chain a Second grep

Filter again to remove every 9.

jQuery
var arr = [1, 9, 4, 7, 3, 8, 6, 9, 1];

arr = $.grep(arr, function (a) {
  return a !== 9;
});

console.log(arr);  // [1, 4, 7, 3, 8, 6, 1]
Try It Yourself

How It Works

  1. Input. Start from a list that may still contain 9s.
  2. Test. Keep only values where a !== 9.
  3. Reassign. arr = $.grep(...) replaces your variable with the filtered list.
  4. Practice. Chain small filters instead of one complex callback when rules are independent.

Edge Cases & Pitfalls

Check these before filtering real data.

boolean

Return a boolean, not a value

Unlike $.map, returning a number or string does not transform the item — it is only tested for truthiness. Use true/false on purpose.

objects

Plain objects are not supported

$.grep needs array-like input. For object maps, use Object.values(obj) first, or iterate with $.each.

this

this is window

Inside the callback, this is the global object — not the current element. Use the first argument for the value.

native

Prefer Array.filter in modern JS

On true arrays, arr.filter(fn) is native and clear. Keep $.grep when you need invert or array-like input in a jQuery codebase.

Browser Support

jQuery.grep() is a data utility available since jQuery 1.0+ in all browsers that load jQuery. It does not depend on a special DOM API — only on jQuery being present.

✓ jQuery 1.0+ · All browsers with jQuery

jQuery.grep()

Works wherever jQuery runs in the browser. For modern pure-array code without jQuery, Array.prototype.filter is the native alternative.

100% Browser support
Google Chrome All versions · Desktop & Mobile
Full support
Mozilla Firefox All versions · Desktop & Mobile
Full support
Apple Safari All versions · macOS & iOS
Full support
Microsoft Edge All versions · Chromium & Legacy
Full support
Internet Explorer IE 6+ · Legacy environments
Full support
Opera All modern versions
Full support
$.grep() Browsers

Bottom line: Use $.grep(arr, fn) in jQuery apps. Use arr.filter(fn) when you only need native array filtering.

Performance Notes

ApproachCostBest for
$.grep(arr, fn)O(n)Filter once over n items
Chained grepsO(n + m + …)Clear multi-step rules
arr.filter(fn)O(n)Native arrays without invert

One pass is enough for a single rule. Chain greps only when each step is easier to read — combine into one callback if the list is huge and you need every micro-optimization.

Key Takeaways

  • Role: $.grep(arr, fn) → new filtered array.
  • Callback: return true/false (not a new value).
  • Invert: third arg true keeps failed tests.
  • Safe: source array is not mutated.

One line: use $.grep to select items with a boolean test — flip with invert, and use $.map when you need to change values.

Frequently Asked Questions

jQuery.grep(array, callback) returns a new array of elements for which your callback returns true. The original array is never modified. It is a static filter utility for array-like collections.
A boolean. Return true to keep the element (when invert is false or omitted). Return false to drop it. Unlike $.map(), you do not return transformed values — only a pass/fail decision.
When invert is true, $.grep() keeps elements where the callback returns false instead of true. Use it when the rejection rule is simpler to write than the keep rule.
With invert false (the default), $.grep() behaves like Array.filter() on arrays. $.grep() also accepts array-like objects with a length property and adds the optional invert flag. Array.filter() is native and has no invert option.
No. Unlike $.each() or $.map(), $.grep() only searches array-like objects — arrays and objects with numeric indexes and a length. Filter Object.values(obj) if you need object data.
$.grep() selects existing elements with a boolean test and returns a subset of the same values. $.map() transforms every item and can change values, skip with null, or flatten nested arrays.
Yes, if jQuery is loaded in that environment. $.grep() is a pure data utility — it does not need a DOM. Many Node setups still prefer native Array.filter() instead.

Next: extend()

Merge objects and defaults with jQuery’s extend utility.

extend tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful