Wilson Page

Front-end developer at FT Labs, within the Financial Times. Chatting about JavaScript, CSS, Web-Apps and other goodness. Follow me on Twitter.
Front-end developer at FT Labs, within the Financial Times. Chatting about JavaScript, CSS, Web-Apps and other goodness. Follow me on Twitter.
  • Contact
  • ask me anything
  • rss
  • archive
  • [quick example] jQuery’s $.map() function

    I have often seen references to ‘map’ in javascript and not really taken the time to fully understand what it means.

    What is map?

    map loops over an array and runs a function on each element in the array. What ever you return from that function will replace the element in the current position. The output of the $.map() is the new array after each element has been manipulated though your ‘iterator’ function.

    Map is available natively in later versions of Javascript (IE9+) but not in older browsers, so in the meantime we have to use jQuery’s $.map() method to ensure cross browser compatibility.

    Basic Example

    var result = $.map( [1,2,3,4], function (a) { 
      return a * 2; 
    });
    
    // result => [2,4,6,8]
    


    Working Examples:

    http://jsfiddle.net/WilsonPage/KjPM6/5/

    Hope this was a nice introduction to map and you can see how useful this could be in your own projects :)

    • December 3, 2011 (6:45 am)
    • 10 notes
    • #jquery
    • #javascript
    • #map
    • #quick example
    1. wilsonpage posted this
    Tweet
© 2011–2013 Wilson Page