jQuery jQuery.grep() Method

Beginner
⏱️ 10 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Utility filter

What You’ll Learn

The jQuery.grep() utility finds array elements that pass a test function and returns them in a new array. This tutorial covers syntax, the optional invert flag, five worked examples, comparisons with Array.filter() and $.map(), and pitfalls every beginner should know.

01

Syntax

$.grep(arr, fn)

02

Boolean

Return true/false

03

Invert

Keep failures

04

Index

(value, index)

05

Subset

Same value types

06

Safe

Original unchanged

Introduction

Filtering is one of the most common data tasks: keep the items that match a rule and discard the rest. jQuery provides jQuery.grep() (also written $.grep()) as a static utility that walks an array-like collection, runs your test function on each element, and builds a new array of matches.

The name comes from the Unix grep command, which searches text for patterns. In jQuery, the idea is the same spirit — find what fits — but your “pattern” is any JavaScript function that returns true or false.

Understanding the jQuery.grep() Method

jQuery.grep(array, callback [, invert]) calls your callback for each element with (element, index). When invert is omitted or false, elements where the callback returns true are copied into the result. When invert is true, elements where the callback returns false are kept instead.

Choose $.grep() when you need a filtered subset of an array without transforming values — prices above a threshold, items after a certain index, or everything except a banned value.

💡
Beginner Tip

Think of $.grep as a reusable if test for every slot in an array. Return true to keep the item; return false to skip it. The original array stays untouched.

📝 Syntax

General form of jQuery.grep:

jQuery
jQuery.grep( array, callback(element, index) [, invert ] )
// or
$.grep( array, callback(element, index) [, invert ] )

Parameters

  • array — an array or array-like object (with length and indexed values) to search through.
  • callback — a function that receives (element, index) and must return a boolean. Inside the callback, this refers to the global object (window in browsers).
  • invert (optional) — when true, keep elements where the callback returns false; when false or omitted, keep elements where the callback returns true.

Return value

  • A new array containing the filtered elements.
  • The original array argument is not modified.

Minimal workflow

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

console.log(positives); // [1, 2]

⚡ Quick Reference

GoalCode
Keep matches$.grep(arr, function (n) { return n > 0; })
Use index in test$.grep(arr, function (n, i) { return i > 4; })
Invert (keep failures)$.grep(arr, fn, true)
Callback returnMust be boolean true or false
Mutates original?No — returns a new array
Plain objects?No — array-like only

📋 $.grep vs Array.filter vs $.map

Three tools for shaping arrays — similar goals, different contracts.

$.grep
boolean test

Filter subset; optional invert flag

filter
boolean test

Native arrays only; no invert

$.map
transform

Return new values; null drops items

invert
3rd arg

Unique to $.grep among these three

Examples Gallery

Each example uses $.grep(). Open DevTools or use the Try-it links to run them interactively.

📚 Getting Started

Keep elements that pass a simple boolean test.

Example 1 — Keep Numbers Greater Than Zero

Filter out zero and keep every positive value — the classic intro from the jQuery API docs.

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

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

How It Works

jQuery calls your function for 0, 1, and 2. Only when the callback returns true is the element copied into the new result array.

📈 Practical Patterns

Invert mode, index checks, chained filters, and real-world rules.

Example 2 — Invert: Keep What Fails the Test

Pass true as the third argument to keep elements where the callback returns false.

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

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

How It Works

The same test n > 0 passes for 1 and 2, but with invert: true those are excluded and only 0 remains. Handy when the rejection rule is easier to express than the keep rule.

Example 3 — Filter by Value and Index

Keep items that are not 5 and have an index greater than 4 — from the official jQuery grep demo.

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

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

console.log(filtered.join(", "));
// "6, 1, 9, 4, 7, 3, 8, 6, 9, 1"
Try It Yourself

How It Works

Indexes 0 through 4 are skipped because i > 4 is false. At index 6, the value 5 is excluded even though the index qualifies. Both conditions must pass.

Example 4 — Chain Filters to Remove All Nines

Run a second $.grep on the result of the first pass to strip every remaining 9.

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

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

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

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

How It Works

Each $.grep call returns a new array, so you can reassign arr and pipe the output into the next filter. This mirrors the chained demo on the jQuery API page.

Example 5 — Keep Words Longer Than Three Characters

Filter strings by length — a practical pattern for lists, tags, or user input.

jQuery
var words = ["go", "run", "fly", "jump", "sit", "code"];

var longWords = $.grep(words, function (word) {
  return word.length > 3;
});

console.log(longWords.join(", "));
// "jump, code"
Try It Yourself

How It Works

$.grep works on any array-like collection of values — numbers, strings, objects, or mixed types. The callback decides membership; matched items keep their original value and order relative to each other.

🚀 Common Use Cases

  • Numeric thresholds — keep scores above a minimum or prices within a budget.
  • Index-based slicing — select items after a header row or skip the first N entries with i > N.
  • Blacklist filtering — remove banned IDs, stop words, or duplicate markers from a list.
  • Inverted rules — use the third argument when “everything except X” is simpler to write as a positive test plus invert.
  • Chained cleanup — pipe several grep passes to progressively narrow results.
  • Legacy jQuery codebases — consistent filtering before native Array.filter was widely available.

🧠 How jQuery.grep() Builds the Result

1

Walk array

jQuery iterates from index 0 to length - 1 on the array-like input.

Iterate
2

Run test

Call your callback with (element, index) and read the boolean result.

Test
3

Apply invert

If invert is true, flip the decision — keep items where the callback returned false.

Invert
4

Return new array

Matching elements are copied in order; the source array is left unchanged.

📝 Notes

  • Available since jQuery 1.0 — one of the oldest jQuery utilities.
  • The callback must return an explicit boolean; truthy numbers or strings still work in JavaScript but explicit true/false is clearer.
  • Inside the callback, this is the global object — not the current array element.
  • Only array-like collections are supported; plain objects need Object.values() or $.map first.
  • Duplicate values in the source array are preserved if each passes the test.
  • For transform-and-filter in one step, consider $.map returning null for rejected items.

Browser Support

jQuery.grep() has been part of jQuery since jQuery 1.0+. It works wherever jQuery runs — all modern browsers and legacy IE when paired with a supported jQuery build.

jQuery 1.0+

jQuery jQuery.grep()

Supported in jQuery 1.x, 2.x, and 3.x. Behavior is consistent across browsers because jQuery owns the filtering implementation.

100% With jQuery loaded
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
jQuery.grep() Universal

Bottom line: Safe in any project that already includes jQuery. On modern apps without jQuery, native Array.filter() covers the default (non-invert) case.

Conclusion

The jQuery.grep() utility is jQuery’s dedicated array filter. Write a boolean test, optionally flip it with invert, and get a new array of matches without touching the original data.

Practice the five examples above until returning true vs false feels natural, then explore jQuery.extend() for merging configuration objects.

💡 Best Practices

✅ Do

  • Return explicit true or false from the callback
  • Use invert when the exclusion rule is simpler to write
  • Chain multiple $.grep calls for step-by-step narrowing
  • Prefer native Array.filter in jQuery-free modern code
  • Combine value and index checks when position matters

❌ Don’t

  • Pass plain objects directly — grep expects array-like input
  • Return transformed values — use $.map instead
  • Assume this inside the callback is the current element
  • Mutate the source array when immutability is required
  • Rely on grep when you also need to reshape every item

Key Takeaways

Knowledge Unlocked

Five things to remember about jQuery.grep()

Filter array-like data the jQuery way.

5
Core concepts
02

true keep

Default mode

Pass
🔄 03

invert

Flip decision

Flag
🔢 04

val, index

Both available

Args
05

No objects

Array-like only

Limit

❓ Frequently Asked Questions

jQuery.grep(array, callback) returns a new array containing only the 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 in the result (when invert is false or omitted). Return false to exclude it. Unlike $.map(), you do not return transformed values — only a pass/fail decision.
When invert is true, jQuery.grep() returns elements where the callback returns false instead of true. It is the opposite filter — useful when the rejection rule is simpler to write than the keep rule.
With invert set to false (the default), $.grep behaves like Array.filter() on arrays. jQuery.grep also accepts array-like objects with a length property and adds the optional invert flag. Array.filter() is native and does not support invert.
No. Unlike $.each() or $.map(), $.grep() only searches array-like objects — arrays and objects with a numeric length and indexed values. Use $.grep on Object.values(obj) if you need to filter object data.
jQuery.grep() selects existing elements with a boolean test and returns a subset of the same values. jQuery.map() transforms every item and can change values, drop items with null, or flatten nested arrays.
Did you know?

The name grep comes from the Unix command-line tool that searches text for matching lines. jQuery’s version generalizes that idea: instead of regex patterns, you supply any JavaScript function that returns true or false for each array element.

Continue to jQuery.extend()

Learn how to merge object properties with shallow and deep extend.

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.

6 people found this page helpful