jQuery: $.grep and $.map example and syntax

In this post I'm going to discuss with you the differences between the two array utilities $.grep() and $.map() provided by jQuery. In fact, the former function filters an array and returns a filtered array, while the latter simply applies a function to each item in the array, thus returning a modified array. First of all, these functions are very different. Here are the main differences:

Syntax

$.grep()
$.grep(array, function(index, value) {

  //...

});

The first parameter is the array we want to filter. The second parameter is the numerical index of each array's item. The third parameter is the actual value of each item in the array.

$.map()
$.map(array, function(value, index) {

  //...

});
The first parameter is the array we want to apply a function on its items. The second parameter is the actual value of each item in the array. The third parameter is the numerical index of each item.

Usage

We use $.grep() when we want to apply a filter to an array. Instead, we use $.map() when we want to apply a function to each array's item. For example, given the following unordered list:

<ul id="test">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li>10</li>
</ul>

We can use $.grep() to filter only the list items that contain an even number:

var lis = $('#test li').get();

var grep = $.grep(lis, function(index, value) {
  
  return (lis[value].firstChild.nodeValue % 2 == 0);
  
  
});

The return statement actually applies the filter specified within round brackets.

Instead, if we want to apply a change to the array and return a modified array, we can use $.map(). For example, we could turn the text of each item into a number and sum its value to each item's index:

var map = $.map(lis, function(value, index) {
    
  return ('<li>' + (new Number(value.firstChild.nodeValue) + index) + '</li>');

});

The syntax used inside the function block is identical to the syntax used with $.grep(). The only difference is that we're returning a modified array, not a filtered one. You can see a demo below.

Demo

Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

One thought on “jQuery: $.grep and $.map example and syntax”

  1. Hi....
    You have used the function signature as
    $.grep(lis, function(index, value)

    But, according to the documentation the function syntax is :

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

    It did not cause any error in your code snippet cz you treated "value" parameter as "index" :

    return (lis[value].firstChild.nodeValue % 2 == 0);

    But, for readability purpose, I think you should give exact signature as jquery documentation.

Leave a Reply

Note: Only a member of this blog may post a comment.