Array.prototype.map()

  • Revision slug: JavaScript/Reference/Global_Objects/Array/map
  • Revision title: Array.prototype.map()
  • Revision id: 1654
  • Created:
  • Creator: Inimino
  • Is current revision? No
  • Comment 4 words added, 10 words removed

Revision Content

Summary

Creates a new array with the results of calling a provided function on every element in this array.

Method of Array
Implemented in: JavaScript 1.6 (Gecko 1.8b2 and later)
ECMAScript Edition: ECMA-262 Edition 5

Syntax

var mappedArray = array.map(callback[, thisObject]);

Parameters

callback
Function that produces an element of the new Array from an element of the current one.
thisObject
Object to use as this when executing callback.

Description

map calls a provided callback function once for each element in an array, in order, and constructs a new array from the results. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values.

callback is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed.

If a thisObject parameter is provided to map, it will be used as the this for each invocation of the callback. If it is not provided, or is null, the global object associated with callback is used instead.

map does not mutate the array on which it is called.

The range of elements processed by map is set before the first invocation of callback. Elements which are appended to the array after the call to map begins will not be visited by callback. If existing elements of the array are changed, or deleted, their value as passed to callback will be the value at the time map visits them; elements that are deleted are not visited.

Compatibility

map is a recent addition to the ECMA-262 standard; as such it may not be present in all browsers. You can work around this by inserting the following code at the beginning of your scripts, allowing use of map in implementations which do not natively support it. This algorithm is exactly the one used in Firefox and SpiderMonkey.

if (!Array.prototype.map)
{
  Array.prototype.map = function(fun /*, thisp*/)
  {
    var len = this.length >>> 0;
    if (typeof fun != "function")
      throw new TypeError();

    var res = new Array(len);
    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in this)
        res[i] = fun.call(thisp, this[i], i, this);
    }

    return res;
  };
}

Examples

Example: Pluralizing the words (strings) in an array

The following code creates an array of "plural" forms of nouns from an array of their singular forms.

function makePseudoPlural(single)
{
  return single.replace(/o/g, "e");
}

var singles = ["foot", "goose", "moose"];
var plurals = singles.map(makePseudoPlural);
// plurals is ["feet", "geese", "meese"]
// singles is unchanged

Example: Mapping an array of numbers to an array of square roots

The following code takes an array of numbers and creates a new array containing the square roots of the numbers in the first array.

var numbers = [1, 4, 9];
var roots = numbers.map(Math.sqrt);
// roots is now [1, 2, 3]
// numbers is still [1, 4, 9]

Example: using map generically

This example shows how to use map on a string to get an array of bytes in the ASCII encoding representing the character values:

var a = Array.prototype.map.call("Hello World", 
                                 function(x) { return x.charCodeAt(0); })
// a now equals [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]

{{ languages( { "fr": "fr/R\u00e9f\u00e9rence_de_JavaScript_1.5_Core/Objets_globaux/Array/map", "ja": "ja/Core_JavaScript_1.5_Reference/Global_Objects/Array/map", "pl": "pl/Dokumentacja_j\u0119zyka_JavaScript_1.5/Obiekty/Array/map" } ) }}

Revision Source

<h2 name="Summary">Summary</h2>
<p>Creates a new array with the results of calling a provided function on every element in this array.</p>
<table class="fullwidth-table" style="width: auto;"> <tbody> <tr> <td class="header" colspan="2">Method of <a href="/en/Core_JavaScript_1.5_Reference/Global_Objects/Array" title="en/Core_JavaScript_1.5_Reference/Global_Objects/Array">Array</a></td> </tr> <tr> <td>Implemented in:</td> <td>JavaScript 1.6 (Gecko 1.8b2 and later)</td> </tr> <tr> <td>ECMAScript Edition:</td> <td>ECMA-262 Edition 5</td> </tr> </tbody>
</table>
<h2 name="Syntax">Syntax</h2>
<pre class="eval">var <em>mappedArray</em> = <em>array</em>.map(<em>callback</em>[, <em>thisObject</em>]);
</pre>
<h2 name="Parameters">Parameters</h2>
<dl> <dt><code>callback</code></dt> <dd>Function that produces an element of the new Array from an element of the current one.</dd> <dt><code>thisObject</code></dt> <dd>Object to use as <code>this</code> when executing <code>callback</code>.</dd>
</dl>
<h2 name="Description">Description</h2>
<p><code>map</code> calls a provided <code>callback</code> function once for each element in an array, in order, and constructs a new array from the results. <code>callback</code> is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values.</p>
<p><code>callback</code> is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed.</p>
<p>If a <code>thisObject</code> parameter is provided to <code>map</code>, it will be used as the <code>this</code> for each invocation of the <code>callback</code>. If it is not provided, or is <code>null</code>, the global object associated with <code>callback</code> is used instead.</p>
<p><code>map</code> does not mutate the array on which it is called.</p>
<p>The range of elements processed by <code>map</code> is set before the first invocation of <code>callback</code>. Elements which are appended to the array after the call to <code>map</code> begins will not be visited by <code>callback</code>. If existing elements of the array are changed, or deleted, their value as passed to <code>callback</code> will be the value at the time <code>map</code> visits them; elements that are deleted are not visited.</p>
<h2 name="Compatibility">Compatibility</h2>
<p><code>map</code> is a recent addition to the ECMA-262 standard; as such it may not be present in all browsers. You can work around this by inserting the following code at the beginning of your scripts, allowing use of <code>map</code> in implementations which do not natively support it. This algorithm is exactly the one used in Firefox and SpiderMonkey.</p>
<pre class="eval">if (!Array.prototype.map)
{
  Array.prototype.map = function(fun /*, thisp*/)
  {
    var len = this.length &gt;&gt;&gt; 0;
    if (typeof fun != "function")
      throw new TypeError();

    var res = new Array(len);
    var thisp = arguments[1];
    for (var i = 0; i &lt; len; i++)
    {
      if (i in this)
        res[i] = fun.call(thisp, this[i], i, this);
    }

    return res;
  };
}
</pre><h2 name="Examples">Examples</h2>
<h3 name="Example:_Pluralizing_the_words_.28strings.29_in_an_array">Example: Pluralizing the words (strings) in an array</h3>
<p>The following code creates an array of "plural" forms of nouns from an array of their singular forms.</p>
<pre class="eval">function makePseudoPlural(single)
{
  return single.replace(/o/g, "e");
}

var singles = ["foot", "goose", "moose"];
var plurals = singles.map(makePseudoPlural);
// plurals is ["feet", "geese", "meese"]
// singles is unchanged
</pre>
<h3 name="Example:_Mapping_an_array_of_numbers_to_an_array_of_square_roots">Example: Mapping an array of numbers to an array of square roots</h3>
<p>The following code takes an array of numbers and creates a new array containing the square roots of the numbers in the first array.</p>
<pre class="eval">var numbers = [1, 4, 9];
var roots = numbers.map(Math.sqrt);
// roots is now [1, 2, 3]
// numbers is still [1, 4, 9]
</pre>
<h3 name="Example:_using_map_generically">Example: using <code>map</code> generically</h3>
<p>This example shows how to use map on a <a href="/en/Core_JavaScript_1.5_Reference/Global_Objects/String" title="en/Core_JavaScript_1.5_Reference/Global_Objects/String">string</a> to get an array of bytes in the ASCII encoding representing the character values:</p>
<pre class="eval">var a = Array.prototype.map.call("Hello World", 
                                 function(x) { return x.charCodeAt(0); })
// a now equals [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]
</pre>
<p>{{ languages( { "fr": "fr/R\u00e9f\u00e9rence_de_JavaScript_1.5_Core/Objets_globaux/Array/map", "ja": "ja/Core_JavaScript_1.5_Reference/Global_Objects/Array/map", "pl": "pl/Dokumentacja_j\u0119zyka_JavaScript_1.5/Obiekty/Array/map" } ) }}</p>
Revert to this revision