LA.NET [EN]

Aug 10

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; });
alert(doubled);

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; });
alert(doubled);

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.

4 comments so far

  1. JQGuy
    9:30 am - 8-12-2009

    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. Razvan Ionescu
    11:12 am - 8-12-2009

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

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>