Diiffernece Between Map and Grep Function in jQuery

The main difference between map() and grep() is:

In $.map() you need to loop over each element in an array and modify its value whilst the $. Grep() method returns the filtered array using some filter condition from an existing array.

Both functions work in the manner described below with examples.

Grep() is quite similar to $.Map(). You can find a reference of map() from here: http://www.c-sharpcorner.com/UploadFile/97fc7a/array-of-values-from-an-existing-array-using-map-function-in/.

If you need to filter and remove elements in an array. The fact is filter array from an existing array. Grep() helps you to get a filter array. In other words if you want to delete some items from an array you can do that using Grep().


The $.grep method returns the filtered array. The callback method defined in the above image takes two arguments and is expected to return a Boolean value of true to keep an element or false to have it removed. The first argument specified is the value of the array element (in this example arrNames), and the second argument passed in is the incremental value of the number of times the $.grep() method has looped.

The output is shown in yellow with red border below:


Map() detailed description

In the code segment we have an ordered list with some list elements. We'll try to select all the list elements from there and pass them as an argument into the jQuery Map function.

The basic structure of Map() is: $.map ( array, callback(elementOfArray, indexInArray) )


Callback functions are ideal for use in situations in which a task is performed repeatedly. In this sample application I've used list of elements under the ordered list under here:


And tried to use a Map() utility function. As stated earlier in this document, the Map function makes an array from an existing array. The same functionality is being done here.


The preceding figure shows that map() function accepts selector elements (e.g "li.class") along with the second argument, the callback function (). The callback function () iterates through all items, one by one with the index value. Later down the line the returned array is being appended with a CSS class as shown.

The output of an application is as in the following:


The sample application has been attached as a reference. 

Up Next
    Ebook Download
    View all
    View all