Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between $.map and $.grep in jQuery

What is the difference between $.map and $.grep in jQuery?

I want a simple answer as far as possible.

like image 965
Tarek Saied Avatar asked Jun 05 '11 19:06

Tarek Saied


People also ask

What is the difference between map and grep function in jQuery?

The jQuery map function translates a set of elements in the jQuery object into another set of values in a jQuery array which may, or may not contain elements. The grep() function is used to find an element of an array.

What does grep do in jQuery?

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.

What is difference between each and map in jQuery?

The each method is meant to be an immutable iterator, where as the map method can be used as an iterator, but is really meant to manipulate the supplied array and return a new array. Another important thing to note is that the each function returns the original array while the map function returns a new array.

What is map in jQuery?

The jQuery map() function translates all items in an object or in array to a new array of items. It applies a function to each item of the object or array and maps the results into a new array.


2 Answers

I will assume you mean $.grep and $.map. The difference is that we use $.grep to filter an array while we use $.map to apply a function to each item in the array.

Here is a much better explanation than I can make:

http://onwebdev.blogspot.com/2011/03/jquery-grep-and-map-example-and-syntax.html

like image 117
IAmTimCorey Avatar answered Sep 28 '22 15:09

IAmTimCorey


$.map method can be used as an iterator, but is meant to manipulate the array and return a new array.

var items = ['A','B','C','A'];    

var items = $.map(items, function(item) {
  if (item == 'A') 
    return null;
  return item;
});

items is now new array. ['B','C']

or

var items = $.map(items, function(item) {
  if (item == 'A') 
    return 'A'+'B';
  return item;
});

output will be ['AB', 'B', 'C', 'AB']

$.grep is used for filtering

var items = $.grep(items, function(item) {
      return item != 'A';
    });

items is now ['B','C']

however

var items = $.grep(items, function(item) {
      if (item == 'A') 
        return 'A'+'B';
      return item;
    })

will return ['A', 'B', 'C', 'A'] as it is not producing new stuff - it reduces the existing.

like image 31
Matas Vaitkevicius Avatar answered Sep 28 '22 16:09

Matas Vaitkevicius