jQuery grep – $.grep() Method

jQuery grep – $.grep() Method

jQuery .grep() method is used to filter an array based on a provided condition. The condition is provided by a filter function. For an item to be included in the result the filter function should return true for it.

Syntax of jQuery grep

$.grep( array, function [, invert ] );
Parameter Description
array Required Parameter: array to filter
function(n,i) Required Parameter: It is the filter function that processes each item of the array. The item must return true for the condition, only then it is included in the result. The first parameter (n) of it is the item and the second one (i) is the index.
[, invert ] Optional Parameter: Accepts Boolean values. If false – (default) returns an array consisting of all elements for which the ‘filter function’ returns true. If true – returns an array consisting of all elements for which the ‘filter function’ returns false.

Example 1: jQuery grep to Filter an Array

I have an array [1, 2, 3, 4, 5, 6, 6, 1, 7] and I want to filter those numbers that are greater than 5. The filtered array is shown in a paragraph element.

<p id="result"></p>
<button id="myButton">Filter Array</button>

On the button click event I will use jQuery grep method to filter array. On the filter function I am putting the condition on the return statement like return (n > 5). This means only those numbers greater than 5 will be the part of the new array (here variable newArr).

$("#myButton").click(function (e) {
   var arr = [1, 2, 3, 4, 5, 6, 6, 1, 7];
   newArr = $.grep(arr, function (n, i) {
       return (n > 5);
   });
   $("#result").text("Array is [" + newArr + "]");
);

I will get the new array as [6,6,7] that will be displaced on the paragraph element.

DEMO

jQuery grep “invert” Parameter

In the above code if I use invert parameter values as true, then I will get all element of the array that are less than or equal to 5 that is it inverts the result.

newArr = $.grep(arr, function (n, i) {
       return (n > 5);
}, true);

Here the new array will be [1,2,3,4,5,1].

DEMO

Using Filter Function’s Index Parameter

The Filter function’s definition contains the second parameter (i) as the index parameter. You can also use it in creating conditions.

For example to filter numbers greater than 2 and index less than 5 from the array, the jQuery grep code will be:

var arr = [1, 2, 3, 4, 5, 6, 6, 1, 7];
newArr = $.grep(arr, function (n, i) {
    return (n > 2 && i < 5);
});

DEMO

Example 2: Filtering JSON from jQuery grep Method

I have a json and I want to filter the records that are Brown in color and are priced $30.87.

The JSON is given below:

[
    {
        "Product": "Mini Skirt size 28",
        "Color": "Brown",
        "Price": "$30.87"
    },
    {
        "Product": "Pant size 47",
        "Color": "Brown",
        "Price": "$30.87"
    },	
    {
        "Product": “Pant size 37",
        "Color": "Black",
        "Price": "$26.75"
    },
    {
        "Product": "Coat size 48",
        "Color": "Orange",
        "Price": "$105.60"
    }
];

I can use jQuery .grep() method to filter my records from the json.

<div id="result"></div>
<button id="myButton">Filter JSON</button>

$("#result").click(function (e) {
    var json = [
                  {
                      "Product": "Mini Skirt size 28",
                      "Color": "Brown",
                      "Price": "$30.87"
                  },
                  {
                      "Product": "Pant size 47",
                      "Color": "Brown",
                      "Price": "$30.87"
                  },
                  {
                      "Product": "Pant size 37",
                      "Color": "Black",
                      "Price": "$26.75"
                  },
                  {
                      "Product": "Coat size 48",
                      "Color": "Orange",
                      "Price": "$105.60"
                  }
    ];
    newArr = $.grep(json, function (n, i) {
        return (n.Color == "Brown" && n.Price == "$30.87");
    });

    var table =  $("<table>").append("<tr><th>Product</th><th>Color</th><th>Price</th></tr>");
    var tr;
    for (var i = 0; i < newArr.length; i++) {
        tr = $("<tr>");
        tr.append("<td>" + newArr[i].Product + "</td>");
        tr.append("<td>" + newArr[i].Color + "</td>");
        tr.append("<td>" + newArr[i].Price + "</td>");
        table.append(tr);
    }
    $("#result").html(table);
});

After filtering I am looping through the filtered JSON and creating a HTML table to display the JSON data.

The result shown in the HTML table is:

jquery grep filtering json

DEMO DOWNLOAD

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on “WordPress, SEO, jQuery, HTML” and more.