jQuery grep() and inArray()

jQuery provides two utility functions for working with plain JavaScript arrays — $.grep() filters an array based on a condition, and $.inArray() searches for a value in an array. Both work on regular JS arrays, not jQuery DOM selections.

$.grep() — Filter an Array

$.grep() takes an array and a test function. It runs the function on each item and keeps only those where the function returns true.

Syntax

$.grep(array, function(value, index) {
    return condition;  // true = keep, false = remove
}, invert);

// invert (optional): if true, keeps items where condition is FALSE

Basic $.grep() Example

var scores = [42, 78, 56, 91, 34, 65, 88];

// Keep only scores above 60
var passing = $.grep(scores, function(score) {
    return score > 60;
});

console.log(passing);   // [78, 91, 65, 88]

Diagram: $.grep() Filtering

  Input:  [42, 78, 56, 91, 34, 65, 88]
  Test:   value > 60

  42  → false → removed
  78  → true  → kept
  56  → false → removed
  91  → true  → kept
  34  → false → removed
  65  → true  → kept
  88  → true  → kept

  Output: [78, 91, 65, 88]

$.grep() with invert = true

var scores = [42, 78, 56, 91, 34, 65, 88];

// Get failing scores (invert = true means keep where condition is FALSE)
var failing = $.grep(scores, function(score) {
    return score > 60;
}, true);

console.log(failing);   // [42, 56, 34]

$.grep() on an Array of Objects

var employees = [
    { name: "Priya",  dept: "Dev",     salary: 75000 },
    { name: "Arjun",  dept: "Design",  salary: 55000 },
    { name: "Meena",  dept: "Dev",     salary: 82000 },
    { name: "Rohit",  dept: "HR",      salary: 48000 }
];

// Get only Dev department employees with salary above 70000
var topDevs = $.grep(employees, function(emp) {
    return emp.dept === "Dev" && emp.salary > 70000;
});

console.log(topDevs);
// [{ name: "Priya", ... }, { name: "Meena", ... }]

Practical: Filter Search Results

$(document).ready(function() {
    var products = ["Laptop", "Mouse", "Keyboard", "Monitor", "Mousepad"];

    $("#searchBox").on("input", function() {
        var query = $(this).val().toLowerCase();

        var results = $.grep(products, function(item) {
            return item.toLowerCase().indexOf(query) !== -1;
        });

        var html = $.map(results, function(item) {
            return "<li>" + item + "</li>";
        }).join("");

        $("#resultList").html(html || "<li>No results</li>");
    });
});

$.inArray() — Search for a Value

$.inArray() searches for a value in an array and returns its index. If the value is not found, it returns -1.

Syntax

$.inArray(searchValue, array, startIndex);

// searchValue → value to find
// array       → the array to search in
// startIndex  → optional, where to start searching (default: 0)

// Returns: index of the found value, or -1 if not found

Basic $.inArray() Examples

var fruits = ["Apple", "Banana", "Cherry", "Dates"];

$.inArray("Cherry", fruits)    // returns 2
$.inArray("Mango", fruits)     // returns -1 (not found)
$.inArray("Apple", fruits)     // returns 0

Using $.inArray() in a Condition

var allowed = ["admin", "editor", "moderator"];
var currentUser = "editor";

if ($.inArray(currentUser, allowed) !== -1) {
    console.log("Access granted.");
} else {
    console.log("Access denied.");
}

Diagram: $.inArray() Search

  Array: ["Apple", "Banana", "Cherry", "Dates"]
  Index:      0         1         2         3

  $.inArray("Cherry", array)
  → checks index 0: "Apple"  → no
  → checks index 1: "Banana" → no
  → checks index 2: "Cherry" → YES! → returns 2

  $.inArray("Mango", array)
  → checks all indices → not found → returns -1

Practical: Avoid Duplicate Entries

$(document).ready(function() {
    var selectedTags = [];

    $(".tag-btn").click(function() {
        var tag = $(this).text();

        if ($.inArray(tag, selectedTags) === -1) {
            selectedTags.push(tag);
            $(this).addClass("selected");
        } else {
            alert(tag + " is already selected!");
        }
    });
});

$.grep() vs $.inArray() — When to Use Each

MethodUse WhenReturns
$.grep()You want to extract a subset of an array based on a conditionNew filtered array
$.inArray()You want to know if a value exists and where it isIndex number or -1

Quick Summary

  • $.grep(array, fn) filters an array — keeps items where the function returns true.
  • Pass true as the third argument to invert the filter (keep items where condition is false).
  • $.inArray(value, array) returns the index of the value, or -1 if not found.
  • Use $.inArray() !== -1 as a boolean check for existence.
  • Both work on plain JavaScript arrays, not jQuery DOM objects.

Leave a Comment

Your email address will not be published. Required fields are marked *