38

I am trying to get a better understanding of the jQuery.map function.

So in general terms .map takes a array and "maps" it to another array of items.

easy example:

$.map([0,1,2], function(n){
    return n+4;
});

results in [4,5,6]

I think I understand what it does. I want to under why would someone need it. What is the practical use of this function? How are you using this in your code?

RedWolves
  • 10,379
  • 12
  • 49
  • 68

7 Answers7

36

Mapping has two main purposes: grabbing properties from an array of items, and converting each item into something else.

Suppose you have an array of objects representing users:

var users = [
  { id: 1, name: "RedWolves" },
  { id: 2, name: "Ron DeVera" },
  { id: 3, name: "Jon Skeet" }
];

Mapping is a convenient way to grab a certain property from each item. For instance, you can convert it into an array of user IDs:

var userIds = $.map(users, function(u) { return u.id; });

As another example, say you have a collection of elements:

var ths = $('table tr th');

If you want to store the contents of those table headers for later use, you can get an array of their HTML contents:

var contents = $.map(ths, function(th) { return th.html(); });
Ron DeVera
  • 14,394
  • 6
  • 41
  • 36
  • Cool. You should add tips to: http://stackoverflow.com/questions/182630/jquery-tips-and-tricks – cllpse Apr 02 '09 at 07:53
26

$.map is all about converting items in a set.

As far as the DOM, I often use it to quickly pluck out values from my elements:

var usernames = $('#user-list li label').map(function() {
    return this.innerHTML;
})

The above converts the <label> elements inside a list of users to just the text contained therein. Then I can do:

alert('The following users are still logged in: ' + usernames.join(', '));
JPot
  • 4,175
  • 4
  • 23
  • 22
  • 9
    [$.map](http://api.jquery.com/jquery.map/) and [.map()](https://api.jquery.com/map/) are different functions. You are referring to `$.map` and the example provided is of `.map()` – T J May 08 '14 at 07:37
  • 5
    The code provided in the example won't work as is because you first need to convert the mapped list into a native array using .get(). Here is the corrected code: var usernames = $('#user-list li label').map(function() { return this.innerHTML; }).get(); – thdoan May 27 '14 at 03:47
6

Map is a high-order function, that enables you to apply certain function to a given sequence, generating a new resulting sequence containing the values of each original element with the value of the applied function.

I often use it to get a valid selector of all my jQuery UI panels for example:

var myPanels = $('a').map(function() { 
  return this.hash || null; 
}).get().join(',');

That will return a comma separated string of the panels available in the current page like this:

"#home,#publish,#request,#contact"

And that is a valid selector that can be used:

$(myPanels);// do something with all the panels
Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
4

Example:

$.map($.parseJSON(response), function(item) {     
    return { value: item.tagName, data: item.id };
})

Here server will be returning the "response" in JSON format, by using $.parseJSON it is converting JSON object to Javascript Object array.

By using $.map for each object value it will call the function(item) to display the result value: item.tagName, data: item.id

quamrana
  • 37,849
  • 12
  • 53
  • 71
1

Recently I discovered an excellent example of .map in a practical setting.

Given the question of How to append options to a selectbox given this array (or another array):

selectValues = { "1": "test 1", "2": "test 2" };

this StackOverflow answer uses .map:

$("mySelect").append(
  $.map(selectValues, function(v,k) {
     return $("<option>").val(k).text(v);
  })
);
Community
  • 1
  • 1
random_user_name
  • 25,694
  • 7
  • 76
  • 115
1

Here's one thing you could use it for.

$.map(["item1","item2","item3"], function(n){
    var li = document.createElement ( 'li' );
    li.innerHTML = n;
    ul.appendChild ( li );
    return li;
});
Jamie
  • 5,994
  • 1
  • 18
  • 15
0

Converting code values to code text would be a possible use. Such as when you have a select list and each indexed value has a corresponding code text.

AaronLS
  • 37,329
  • 20
  • 143
  • 202