jQuery: The Write Less, Do More JavaScript Library

Utilities/jQuery.map

From jQuery JavaScript Library

Jump to: navigation, search

« Back to Utilities

jQuery.map( array, callback )

Translate all items in an array to another array of items.
The translation function that is provided to this method is called for each item in the array and is passed one argument: The item to be translated. The function can then return the translated value, 'null' (to remove the item), or an array of values - which will be flattened into the full array.
Arguments:
arrayArray
The Array to translate.
callbackFunction
The function to process each item against. The argument to the function is the list item. The function can return any value. Optionally, this argument may be a string rather than a function. If the argument is a string, it is treated as a short "lambda-form" function, with "a" representing the list item. For example, "a * a" may be passed instead of "function(a){ return a * a; }".
function callback(elementOfArray, indexInArray) {
  var replacementValue;

  this; // unmapped

  return replacementValue;
}

Examples:
Maps the original array to a new one and adds 4 to each value.

    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, "a + a");
    $("span").text(arr.join(", "));

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="../jquery-latest.js"></script>
  
  <script>
  $(document).ready(function(){
    
    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, "a + a");
    $("span").text(arr.join(", "));

  });
  </script>
  <style>
  div { color:blue; }
  p { color:green; margin:0; }
  span { color:red; }
  </style>
</head>
<body>
  <div></div>
  <p></p>
  <span></span>
  
</body>
</html>

Maps the original array to a new one and adds 4 to each value.

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

[4, 5, 6]

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;
});

[2, 3]

Maps the original array to a new one, each element is added with it's original value and the value plus one.

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

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

Maps the original array to a new one, each element is squared.

$.map( [0,1,2,3], "a * a" );

[0, 1, 4, 9]

NameType