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.

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’: