SyntaxStudy
Sign Up
jQuery jQuery $.grep() — Array Filtering
jQuery Intermediate 4 min read

jQuery $.grep() — Array Filtering

$.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 true inverts 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.

Example
// Filter numbers above a threshold
var scores = [42, 88, 73, 95, 61, 55, 90];
var passing = $.grep(scores, function (score) {
    return score >= 70;
});
console.log(passing); // [88, 73, 95, 90]

// Invert — get failing scores
var failing = $.grep(scores, function (score) {
    return score >= 70;
}, true); // invert!
console.log(failing); // [42, 61, 55]

// Filter objects by property
var users = [
    { name: 'Alice', active: true  },
    { name: 'Bob',   active: false },
    { name: 'Carol', active: true  }
];
var activeUsers = $.grep(users, function (u) {
    return u.active;
});
console.log(activeUsers.length); // 2
Pro Tip

Remember $.grep() callback order is (element, index) — the reverse of $.each() — to avoid subtle bugs.