39

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?

7 Answers 7

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(); });
Sign up to request clarification or add additional context in comments.

1 Comment

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(', '));

2 Comments

$.map and .map() are different functions. You are referring to $.map and the example provided is of .map()
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();
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

1 Comment

That's a nice use case!
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

Comments

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;
});

Comments

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);
  })
);

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.