Find element/object in an array using jQuery.grep()


By: Rakesh Girase | May 15, 2015

Introduction

In this blog, will have walk through about easiest way to find the element/object in a JavaScript array which satisfy the filter condition.

Background

Most of the time, we come to scenario where we used JavaScript array having elements/objects and we need to filter it with specific condition and return list of array element/objects. In this case implementing loop and push elements/array into temporary array would be time consuming , So we can go with  quick approach of in build method of jQuery i.e. “grep()”.

Details

jQuery provides method called “grep()”, which Finds the elements of an array which satisfy a filter function. The original array is not affected.

 

Format:

jQuery.grep( array, function [, invert ] )

 

array

Type: Array

The array to search through.

 

function

Type: Function( Object elementOfArray, Integer indexInArray ) => Boolean

The function to process each item against. The first argument to the function is the item, and the second argument is the index. The function should return a Boolean value.  this will be the global window object.

 

invert

Type: Boolean

The $.grep() method removes items from an array as necessary so that all remaining items pass a provided test. The test is a function that is passed an array item and the index of the item within the array. Only if the test returns true will the item be in the result array.

The filter function will be passed two arguments: the current array item and its index. The filter function must return ‘true’ to include the item in the result array.

Example: Array of numeric element and Filter element having number is greater than 5 and return the resulting array.

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>jQuery.grep demo</title>
    <style>
        div {
            color: blue;
        }

        p {
            color: green;
            margin: 0;
        }

        span {
            color: red;
        }
    </style>
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
    Array Elements:
    <div></div>
    <br />
    Result:
    <p></p>
    
    <script>
        var numberArray = [1,2,3,4,5,6,7,8,9,10,11,12];
        $("div").text(numberArray.join(", "));

        var resultAarray = jQuery.grep(numberArray, function (n, i) {
            return (n >5);
        });

        $("p").text(resultAarray.join(", "));
        
    </script>

</body>
</html>

Result:

Array Elements:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12

Result:
6, 7, 8, 9, 10, 11, 12







Example: Array of numeric element and Filter element having number is greater than 5 along with Index is greater than 5 .Return the resulting array.

var resultAarray = jQuery.grep(numberArray, function (n, i) {
            return (n >5 && i>7);
        });










Result:

Result:
9, 10, 11, 12










Example: Array of Student objects and Filter students having score greater than 50.

(If “invert” is false, or not provided, then the function returns an array consisting of all elements for which “callback” returns true.)

var studentList = [
                            { "firstName": "John", "score": "30" },
                            { "firstName": "Anna", "score": "40" },
                            { "firstName": "Peter", "score": "50" },
                            { "firstName": "Arco", "score": "60" },
                            { "firstName": "Om", "score": "70" }
                       ];

        $("div").text(JSON.stringify(studentList));

        var resultAarray = jQuery.grep(studentList, function (n, i) {
            return (n.score>50);
        },false);

        $("p").text(JSON.stringify(resultAarray));










Result:

Array Elements:
[{"firstName":"John","score":"30"},{"firstName":"Anna","score":"40"},{"firstName":"Peter","score":"50"},{"firstName":"Arco","score":"60"},{"firstName":"Om","score":"70"}]

Result:
[{"firstName":"Arco","score":"60"},{"firstName":"Om","score":"70"}]

Example: Array of Student objects and Filter students having score is not greater than 50.

(If “invert” is true, then the function returns an array consisting of all elements for which “callback” returns false.)

var studentList = [
                            { "firstName": "John", "score": "30" },
                            { "firstName": "Anna", "score": "40" },
                            { "firstName": "Peter", "score": "50" },
                            { "firstName": "Arco", "score": "60" },
                            { "firstName": "Om", "score": "70" }
                       ];

        $("div").text(JSON.stringify(studentList));

        var resultAarray = jQuery.grep(studentList, function (n, i) {
            return (n.score>50);
        },true);

        $("p").text(JSON.stringify(resultAarray));

Result:

Array Elements:
[{"firstName":"John","score":"30"},{"firstName":"Anna","score":"40"},{"firstName":"Peter","score":"50"},{"firstName":"Arco","score":"60"},{"firstName":"Om","score":"70"}]

Result:
[{"firstName":"John","score":"30"},{"firstName":"Anna","score":"40"},{"firstName":"Peter","score":"50"}]

Summary

Hope this post will be helpful for returning resulting array from Array variable with specified criteria.

Please post you  reply .

This post has been viewed 16,704 times

7 thoughts on “Find element/object in an array using jQuery.grep()

Leave a Reply

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


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>