How to Use jQuery $.grep() to Filter an Array

The jQuery $.grep() method is a utility function designed to filter arrays by removing elements that do not satisfy a specific condition. This article covers the syntax of $.grep(), how its callback function works, how to use the optional inversion parameter to keep unmatched items, and practical code examples demonstrating array filtering for both primitive values and objects.

Understanding $.grep() Syntax

The basic syntax for $.grep() is:

jQuery.grep(array, function(elementOfArray, indexInArray) [, invert])
  • array: The array you want to filter.
  • function(elementOfArray, indexInArray): A callback function executed for each element. It should return a boolean value (true to keep the item, false to discard it). Note that the element comes first and the index comes second.
  • invert (optional): A boolean flag. If set to false (default), the function keeps elements where the callback returns true. If set to true, the function inverts the logic, keeping only elements where the callback returns false.

Basic Example: Filtering Numbers

To extract numbers greater than 10 from an array of integers:

const numbers = [5, 12, 8, 130, 44];

const result = $.grep(numbers, function(n, i) {
    return n > 10;
});

console.log(result); 
// Output: [12, 130, 44]

Filtering an Array of Objects

$.grep() is frequently used to filter collections of objects based on specific property values.

const users = [
    { name: "Alice", active: true },
    { name: "Bob", active: false },
    { name: "Charlie", active: true }
];

const activeUsers = $.grep(users, function(user) {
    return user.active === true;
});

console.log(activeUsers);
// Output: [{ name: "Alice", active: true }, { name: "Charlie", active: true }]

Using the invert Parameter

If you need to reject items matching a condition rather than keeping them, pass true as the third argument instead of writing negative logic inside the callback:

const numbers = [1, 2, 3, 4, 5, 6];

// Keep items that are NOT greater than 3
const notGreaterThanThree = $.grep(numbers, function(n) {
    return n > 3;
}, true);

console.log(notGreaterThanThree); 
// Output: [1, 2, 3]

$.grep() vs. Native Array.prototype.filter()

While modern JavaScript natively supports array filtering using Array.prototype.filter(), $.grep() remains useful in legacy codebases or projects heavily utilizing jQuery utilities. Unlike the native method, $.grep() provides the built-in invert parameter and handles edge cases where older browsers lack full ECMAScript 5 support.