jQuery API

jQuery.map()

jQuery.map( array, callback(elementOfArray, indexInArray) ) Returns: Array

Description: Translate all items in an array or object to new array of items.

  • version added: 1.0jQuery.map( array, callback(elementOfArray, indexInArray) )

    arrayThe Array to translate.

    callback(elementOfArray, indexInArray)The function to process each item against. The first argument to the function is the array item, the second argument is the index in array The function can return any value. Within the function, this refers to the global (window) object.

  • version added: 1.6jQuery.map( arrayOrObject, callback( value, indexOrKey ) )

    arrayOrObjectThe Array or Object to translate.

    callback( value, indexOrKey )The function to process each item against. The first argument to the function is the value; the second argument is the index or key of the array or object property. The function can return any value to add to the array. A returned array will be flattened into the resulting array. Within the function, this refers to the global (window) object.

The $.map() method applies a function to each item in an array or object and maps the results into a new array. Prior to jQuery 1.6, $.map() supports traversing arrays only. As of jQuery 1.6 it also traverses objects.

Array-like objects — those with a .length property and a value on the .length - 1 index — must be converted to actual arrays before being passed to $.map(). The jQuery library provides $.makeArray() for such conversions.

// The following object masquerades as an array.
var fakeArray = {"length": 1, 0: "Addy", 1: "Subtracty"};

// Therefore, convert it to a real array
var realArray = $.makeArray( fakeArray )

// Now it can be used reliably with $.map()
$.map( realArray, function(val, i) {
  // do something 
});

The translation function that is provided to this method is called for each top-level element in the array or object and is passed two arguments: The element's value and its index or key within the array or object.

The function can return:

  • the translated value, which will be mapped to the resulting array
  • null, to remove the item
  • an array of values, which will be flattened into the full array

Examples:

Example: A couple examples of using .map()

<!DOCTYPE html>
<html>
<head>
  <style>
  div { color:blue; }
  p { color:green; margin:0; }
  span { color:red; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <div></div>
  <p></p>
  <span></span>
  
<script>
    var arr = [ "a", "b", "c", "d", "e" ];
    $("div").text(arr.join(", "));

    arr = jQuery.map(arr, function(n, i){
      return (n.toUpperCase() + i);
    });
    $("p").text(arr.join(", "));

    arr = jQuery.map(arr, function (a) { 
      return a + a; 
    });
    $("span").text(arr.join(", "));

</script>

</body>
</html>

Demo:

Example: Map the original array to a new one and add 4 to each value.

$.map( [0,1,2], function(n){
   return n + 4;
 });

Result:

[4, 5, 6] 

Example: Maps the original array to a new one and adds 1 to each value if it is bigger then zero, otherwise it's removed.

$.map( [0,1,2], function(n){
   return n > 0 ? n + 1 : null;
 });

Result:

[2, 3] 

Example: Map the original array to a new one; each element is added with its original value and the value plus one.

$.map( [0,1,2], function(n){
   return [ n, n + 1 ];
 });

Result:

[0, 1, 1, 2, 2, 3] 

Example: Map the original object to a new array and double each value.


var dimensions = { width: 10, height: 15, length: 20 };
dimensions = $.map( dimensions, function( value, index ) {
  return value * 2;
}); 

Result:

[20, 30, 40] 

Example: Map an object's keys to an array.


var dimensions = { width: 10, height: 15, length: 20 },
    keys = $.map( dimensions, function( value, index ) {
      return index;
    }); 

Result:

["width", "height", "length"] 

Example: Maps the original array to a new one; each element is squared.


$.map( [0,1,2,3], function (a) { 
  return a * a; 
});

Result:

[0, 1, 4, 9] 

Example: Remove items by returning null from the function. This removes any numbers less than 50, and the rest are decreased by 45.


$.map( [0, 1, 52, 97], function (a) {
  return (a > 50 ? a - 45 : null); 
});

Result:

[7, 52] 

Example: Augmenting the resulting array by returning an array inside the function.

var array = [0, 1, 52, 97];
array = $.map(array, function(a, index) {
  return [a - 45, index];
}); 

Result:

[-45, 0, -44, 1, 7, 2, 52, 3] 

Support and Contributions

Need help with jQuery.map() or have a question about it? Visit the jQuery Forum or the #jquery channel on irc.freenode.net.

Think you've discovered a jQuery bug related to jQuery.map()? Report it to the jQuery core team.

Found a problem with this documentation? Report it on the GitHub issue tracker

  • Anonymous

    I filed a bug and patch about this a while back about the binding of this function, which was rejected. The current binding: “[this] will be the global window object.” violates the principle of least surprise, for no added benefit.

    The other iteration methods, both on jQuery and on jQuery.prototype set [this] to be the current iteration’s element. I can see not wanting to change an API that could break compatibility, but any code that relies on the current [window] scope behavior probably doesn’t exist, or is working by coincidence.

    • burtonkent

      I wonder if there can at least be a way to override this behavior without having to code it?

  • Anonymous

    Would be nice to have an optional flag to specify whether arrays returned by the function are flattened, or just treated as an ‘element’ of the new array. Otherwise doing a map on an array of arrays to another array of arrays doesn’t appear to be as simple.

    • http://pettys.myopenid.com/ pettys

      This was a stumbling block for me when working with an array of arrays.

    • http://kflorence.myopenid.com/ Kyle Florence

      If you want your array value to be returned as an array instead of being flattened, just wrap it in an array (so it becomes an array with one element, which is your array) like so:

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

      Returns: [[0, 1], [1, 2], [2, 3], [3, 4]]

      • Ilya P.

        Thanks! This is just what I was looking for.

    • Noglorp

      Or not flatten arrays are all, that is an EPIC wtf.

      • Noglorp

        Also, removing null values is another WTF. This is map not filter, can be keep it canonical please?

  • Nabil Redmann

    another example, nothing like that is mentioned:

    var arrImageURLs = $.map($(“li > img”), function(e, i){ return $(e).attr(“src”); });

    Before you would have used .each() for this mapping case.

  • Tori Tori

    can someone post an example that return two dimensional array using .map

    • Asfd

      return a new object containing multiple attributes

      • http://twitter.com/iakomus Diego Lavayen Alarcó

        why the documentation says it returns an array… :-/

        • http://www.learningjquery.com/ Karl Swedberg

          It does return an array. It does not return a multi-dimensional array, however. When the callback function encounters a “nested” array, that array is “flattened into the full array.”

  • Yukulélé

    to use with string :

    var str="Hello World"
    str2=$.map(str.split(""),function(char,i){...}).join("");

  • lukom

    Are there in jQuery something like this:

    $('input:checked').map(function(){return $(this).val();}).join(',')

    ? I mean map() function over jQuery elements?

  • lukom

    Are there in jQuery something like this:

    $('input:checked').map(function(){return $(this).val();}).join(',')

    ? I mean map() function over jQuery elements?