jQuery grep, match functions to filter arrays

JQuery provides us different functions to filter the arrays data. Here I am discussing about two jQuery functions.

Those are grep() and match() jQuery functions.

 

grep() method parses all the elements of the array and invokes a callback function on each element.

grep() method syntax:

                                        grep(array, "callbackfunction")

 

match()  function is used return the strings that matches the strings specified in the match() method.

match() method syntax:

                                       string.match("regular expression")

 

In the below code you can simple usuage of grep() and match() methods.

 

<html>
    <head>
        <title>javascript arrays using jQuery grep() and match() functions</title>
        <script type="text/javascript" src="jquery.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {


                var elems = ['Asp.Net', 'Vb.Net', 'C#.Net', 'Asp.Net MVC', 'Sharepoint']
                //displaying array elements whose length is greater than 6
                elems = $.grep(elems, function(n) { return n.length > 6 });
                $('#divgrep').html(elems.join("<br/>"));


                var elems1 = ['Asp.Net', 'Vb.Net', 'C#.Net', 'Asp.Net MVC', 'Sharepoint']
                //displaying array elements whose starting from A to C
                elems1 = $.grep(elems1, function(n) { return n.match(/^[A-S]/) });
                $('#divmatch').html(elems1.join("<br/>"));
               
               
            });   
        </script>
    </head>
    <body>
      <p>Array Elements whose length is greater than 6 by using grep() jQuery function</p>
      <div id="divgrep"></div>
     
      <p>Array Elements who are starting from A to C  by using match() jQuery function</p>
      <div id="divmatch"></div>
     
    </body>
</html>

 

$.grep(elems, function(n) { return n.length > 6 }); will return array of elements whose length is greater than 6. Here we are parseing each array element to callback function of grep() method and callback function function(n) { return n.length > 6 } will return array elements whose length is greater than 6.

 

$.grep(elems1, function(n) { return n.match(/^[A-S]/) }); will return array of elements who are starting from letter "A" to "S". Here we are parseing each array element to callback function of grep() method. In the callback function we are using match() method where we are specifying the our regular expression. n.match(/^[A-S]/) will take input "n" as string and return same string if it has start letter between "A" and "S".

 

Download source code: jQuery-grep-match.zip (35.86 kb)