map, grep, jQuery

API: map & grep



API: map & grep

Posted by admin | Web Design | Tuesday 31 March 2009 8:36 pm

API: map & grep

 

map and grep are two utilities that are extremely useful if you know how to use them, but more often that not, I see more convoluted code written to achieve the effect of these functions.

 

Historically, I believe that John Resig was inspired by the Perl functions of the same name – which are basic building blocks of the Perl programming language. Let’s look at how you can use these functions.

valant

 

Map

 

Map comes in two flavours: $.map(array, callback) and $(‘element’).map(callback). The first allows you to iterate vanilla arrays, and the second to loop through elements.

 

The $.map function returns a plain array, where as $(‘element’).map returns a jQuery wrapped array, which means you still have access to functions like each.

 

A really powerful use of map to pull out a comma separated list of element IDs from a list of anchor element, as often explained by ajpiano on the #jquery IRC channel:

 

var panelIds = $('a').map(function() {    return this.hash;  }).get().join(",")  
// returns: #tabA,#tabB,#tabC

This can be useful to collect the list of tabs the links are related to as seen in the jQuery look: Tim Van Damme tutorial last month.

 

Grep

 

grep is similar to $.map in that it will return an array. It’s only available in the $.grep flavour, and allows you to create new arrays when a certain condition is met (which is defined in the callback).

 

Note that in the this keyword is a reference to the window object, rather than the current item as you might expect.

 

A contrived example could be to create a comma separated list of IDs that start with the word ‘tab’:

 

var g = $.grep($('a').get(), function (item) {   
  return /^#tab/.test(item.hash); });  var panelIds = $.map(g, function (item) {
     return item.hash }).join(',');


These are pretty useful utilities for spe
cific problem.

 

 Valant uses actively jQuery in developming new features.

 Mail this post

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment