The $.grep() method is a utility used to **filter** a JavaScript array by
searching for elements that meet a specific condition. It is very similar to the native
Array.filter() method in modern JavaScript.
The method takes three arguments: the array, a filter function, and an optional "invert" boolean.
$.grep(array, function(element, index) {
// Return true to keep the element
// Return false to remove it
}, invert);
Suppose you have an array of ages and you only want to keep those that are 18 or older.
var ages = [12, 25, 18, 5, 40, 31];
var adults = $.grep(ages, function(val, i) {
return val >= 18;
});
// Result: [25, 18, 40, 31]
console.log(adults);
If you pass true as the third argument, the logic is reversed. Elements that
**fail** the condition will be kept, and those that pass will be removed.
var numbers = [1, 5, 10, 15, 20];
// Return only numbers that are NOT greater than 9
var smallNumbers = $.grep(numbers, function(n) {
return n > 9;
}, true); // The 'true' here inverts the logic
// Result: [1, 5]
map() changes the format of data,
grep() simply decides if an item should stay in the list or go. It is purely
for searching and filtering.
Calculating or finding specific objects within a dataset is a common task in dashboard development.
var inventory = [
{ name: "Laptop", stock: 5 },
{ name: "Mouse", stock: 0 },
{ name: "Monitor", stock: 12 }
];
// Find only items that are out of stock
var outOfStock = $.grep(inventory, function(item) {
return item.stock === 0;
});
// Result: [{ name: "Mouse", stock: 0 }]
$.grep() does not modify the original array; it
returns a **new** filtered version. This makes your code safer and prevents accidental
data loss.
for loops for searching.