JQuery: utility functions IX – transforming arrays

The map utility function can be used to translate all the elements contained in the array into other set of items. You’ll find this method useful when you need to transform a collection of items A into items. The function expects two parameters:

  • an array of items that is going to be translated;
  • a callback function which will be called for each item and is responsible for transforming the existing item into a new item.

Here’s a simple example which doubles all the integers contained on an array named arr:

var arr = [1, 2, 3, 4];
var doubled = $.map(arr, function(item) { return item * 2; });

You might be thinking that this is so simple that you could do it by using a simple for. Fair enough…and if I told you that I’d like to receive only the double of elements which aren’t divisible by four? Here’s how you’d do that:

var arr = [1, 2, 3, 4];
var doubled = $.map(arr, function(item) { if( item % 4 === 0 ) return null; return item * 2; });

Returning null removes an item from the final array. Ok, I can hear you thinking! Yes, this is still doable with a simple for and using continue for the cases that don’t matter…And what if I told you that I want the first three multiples of all numbers which aren’t divisible by four? (and I’m talking about a flat array, not an array of arrays). Here’s how you’d do it with this utility method:

var arr = [1,2,3, 4];
var doubled = $.map(arr,
function(item) {
    var items = [];
    var i = 0;
    while (i++ < 3) {
        items[i ] = item * i;
    return items;

Simple and easy, right? For the sake of completeness, I’d like to point out that the callback function receives two arguments: the first (which was used in all the previous samples) references the current item of the array that is being enumerated; the second returns the current position within the array. Keep tuned for more on JQuery.


~ by Luis Abreu on August 10, 2009.

2 Responses to “JQuery: utility functions IX – transforming arrays”

  1. Nice writeup… It would be even nicer if you include the expected results of your array translations in comments. Not every reader has the time to try out your examples…

  2. Dude, there”s a lightbulb where your array index should be.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: