views:

806

answers:

5

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?

+1  A: 

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
+6  A: 

Mapping has two main purposes: grabbing properties from an array of items, and converting each element 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:

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

As another example, say you have an array of elements:

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

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

$.map(ths, function(th){ return th.html(); });
Ron DeVera
Cool. You should add tips to: http://stackoverflow.com/questions/182630/jquery-tips-and-tricks
roosteronacid
A: 

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
+4  A: 

$.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
+1  A: 

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
CMS