Search

API: map & grep

Posted on 25th March 2009 — 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.

Watch

Watch API: map & grep screencast (Alternative flash version)

QuickTime version is approximately 15Mb, flash version is streaming.

View the demo used in the screencast

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

Other Uses?

These are pretty useful utilities for specific problems – if anyone else has any examples of how they use these functions, please show off your code and share! buy cialis