Filtering and Modifying Array elements in JQuery with example


          We could easily filter and modify array entries in JQuery using relevant methods, without writing huge lines of code. Below I have explained its syntax with an simple example code. 

The method that we use to filter array elements in JQuery is $.grep ()
Syntax:  $.grep (array, callback)

  • The $.grep () method is a loop which runs on the array being passed to it and returns a filtered array.
  • The “array” in the above syntax is array name to which you want to apply filter.
  • The “callback” is the function which takes two parameters, and returns Boolean value. The syntax of this goes as below:
             Function (arrayEntry, index) {
             [Condition which applies filter and returns True/False]
             }

  • arrayEntry is the actual entry value, and index is the index of the array entry.
  • If the callback function returns true, then $.grep () method adds that entry to the returning array, otherwise it simply removes that entry.

The method that we use to modify array elements in JQuery is $.map ()
Syntax:  $.map (array, callback)

  • The $.map () method is a loop which runs on the array being passed to it and returns a modified array.
  • The “array” in the above syntax is array name to which you want apply filter.
  • The “callback” is the function which takes two parameters, and returns the modified value. The syntax of this goes as below:

              Function (arrayEntry, index) {
              [Code to modify the array entry and return the modified value]
              }

  • arrayEntry is the actual entry value, and index is the index of the array entry.

Implementation:
         Let us consider a scenario where you have to filter out students whose name starts with letter “A” and convert them to uppercase and show them, on click of a button.

Step 1: 
         Download JQuery Library from https://jquery.com/download/ and copy the files to one of          your project folders as below. I have added minified version of JQuery here, you can add the full   version if you want.

Step 2: 
          Add a Web Form to the website as below and name it as Home.aspx.


Step 3: 
         Add reference of JQuery file to Home.aspx as shown below.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
</head>
<body>
</body>
</html>

Step 4: 
        Now create two div tags with ids’, one for showing the original array and the second one is for showing the filtered and modified array and a button with OnclientClick event.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
    <script src="Scripts/Scripts.js" type="text/javascript"></script>
</head>
<body>
    <form id="form1" runat="server">
    <div id="OriginalArray">
    </div>
    <div id="FilteredAndModifiedArray">
    </div>
          <asp:Button ID="btnFilter" runat="server" Text="FilterAndModify"         
           OnClientClick="filterAndModify();return false;" />
    </form>
</body>
</html>

Step 5: 
         To define the array and bind them back to the divs’ , let us create a separate JavaScript file, and add it’s reference to the Home.aspx ,just as you did for JQuery library file, as below.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
    <script src="Scripts/Scripts.js" type="text/javascript"></script>
</head>
<body>
</body>
</html>

Step 6:
          Now open up the JavaScript file that we created in step 5 and start writing the code as below.

var studentNames = ["Akhil", "Anthony", "Bob", "Bhavani", "Cherry"];

$(document).ready(function () {
    $("#OriginalArray").append('<li>OriginalArray</li>');
    $("#OriginalArray").append('<li>--------------------------------</li>');

    /*binding the original student names to div:OriginalArray*/
    $.each(studentNames, function (index, item) {
        $("#OriginalArray").append('<li>' + item + '</li>');
    });

    $("#OriginalArray").append('<li>-------------------</li>');
});

function filterAndModify() {
    var filetredAndModifiedStudents = [];

    $("#FilteredAndModifiedArray").append('<li>FilteredAndModifiedArray</li>');
    $("#FilteredAndModifiedArray").append('<li>--------------------------------</li>');

    /*filtering out students whose name starts with 'A'*/
    filetredAndModifiedStudents = $.grep(studentNames, function (item, index) {
        if (item.charAt(0) == 'A') {
            return true;
        } else {
            return false;
        }
    });

    /*modifying the student names to upper case*/
    filetredAndModifiedStudents = $.map(filetredAndModifiedStudents, function (item, index) {
        return item.toUpperCase();
    });

    /*binding the filered and modified student names to div:FilteredAndModifiedArray*/
    $.each(filetredAndModifiedStudents, function (index, item) {
        $("#FilteredAndModifiedArray").append('<li>' + item + '</li>');
    });
}

In the above code we are defining a global array “studentNames”. This is made global because it could be accessible from anywhere in the script file.
In the $(document).ready () function we are running an each loop over studentNames array and binding each item to the div with id “OriginalArray”.So when you run the project, you would see all the items of studentNames array as below.


Now our aim is to filter out student names whose name starts with letter ‘A’ and modify those names to upper case and bind it to the div with id “FilteredAndModifiedArray” on click of “FilterAndModify” button.

So if you observe the definition of filterAndModify () method,
We are defining a filetredAndModifiedStudents array to store the filtered names.

After that, if you observe the below block of code,

    /*filtering out students whose name starts with 'A'*/
    filetredAndModifiedStudents = $.grep(studentNames, function (item, index) {
        if (item.charAt(0) == 'A') {
            return true;
        } else {
            return false;
        }
    });

We are implementing $.grep() method as we discussed in the beginning of the article. The condition in the call back function checking if the first letter of the student name being passes is ‘A’ or not. If it is yes it returns true. If not it returns false. The grep method is wise enough to store the student name in the filetredAndModifiedStudents array when the call back function returns true and to ignore the name, when false has been returned.
After that, if you observe the below block of code,

    /*modifying the student names to upper case*/
    filetredAndModifiedStudents = $.map(filetredAndModifiedStudents, function (item, index) {
        return item.toUpperCase();
    });

We are implementing $.map () method as we discussed in the beginning of the article.
The callback method here modifies the value of the array to uppercase and returns the same. This returned item gets stored back to filetredAndModifiedStudents array.

After that, if you observe the below block of code,

    /*binding the filered and modified student names to div:FilteredAndModifiedArray*/
    $.each(filetredAndModifiedStudents, function (index, item) {
        $("#FilteredAndModifiedArray").append('<li>' + item + '</li>');
    });

All we are trying to do is bind the filtered and modified student names to the div with id “FilteredAndModifiedArray” by running an each loop over items in filetredAndModifiedStudents array.

So when you click on the FilterAndModify button ,we get to see the following output.


The output is pretty self-explanatory. It is returning “Akhil” and “Anthony” in upper case as they have letter “A” as his first letter

Hope this tutorial explains Filtering and modifying array entries using Jquery in a simpler way with clear example...

Source Code of this Project - Link



Reactions:

0 comments :

Post a Comment