Array.prototype.map()

  • Revision slug: JavaScript/Reference/Global_Objects/Array/map
  • Revision title: Array.prototype.map()
  • Revision id: 1667
  • Created:
  • Creator: evilpie
  • Is current revision? No
  • Comment 5 words added, 1 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
ECMAScript Edition ECMAScript 5th Edition

Syntax

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 other implementations of the standard. 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 specified in ECMA-262, 5th edition, assuming ObjectTypeError, and Array have their original values and that fun.call evaluates to the original value of Function.prototype.call.  {{ var DO_NOT_MODIFY_THE_FOLLOWING_CODE_IN_ANY_WAY = 0; }}

if (!Array.prototype.map) {
  Array.prototype.map = function(fun /*, thisArg */) {
    "use strict";

    if (this == null)
      throw new TypeError('can not convert ' + this + ' to object');

    var t = Object(this);
    var len = t.length >>> 0;
    if (typeof fun != 'function')
      throw new TypeError(fun + ' is not callable');
    
    var result = new Array(len);
    var thisArg = arguments[1];
    for (var i = 0; i < len; i++) {
      if (i in t)
        result[i] = fun.call(thisArg, t[i], i, t);
    }

    return result;
  };
}

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 fuzzyPlural(single) {
  return single.replace(/o/g, 'e');
}

var words = ["foot", "goose", "moose"];
console.log(words.map(fuzzyPlural));

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

Browser compatibility

Based on Kangax's compat tables

{{ CompatibilityTable() }}

Feature Firefox (Gecko) Chrome Internet Explorer Opera Safari
Basic support {{ CompatVersionUnknown() }} {{ CompatVersionUnknown() }} 9 {{ CompatVersionUnknown() }} {{ CompatVersionUnknown() }}
Feature Firefox Mobile (Gecko) Android IE Mobile Opera Mobile Safari Mobile
Basic support {{ CompatUnknown() }} {{ CompatUnknown() }} {{ CompatUnknown() }} {{ CompatUnknown() }} {{ CompatUnknown() }}

{{ 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="standard-table"> <thead> <tr> <th class="header" colspan="2">Method of <a href="/en/JavaScript/Reference/Global_Objects/Array" title="en/JavaScript/Reference/Global_Objects/Array"><code>Array</code></a></th> </tr> </thead> <tbody> <tr> <td>Implemented in</td> <td>JavaScript 1.6</td> </tr> <tr> <td>ECMAScript Edition</td> <td>ECMAScript 5th Edition</td> </tr> </tbody>
</table>
<h2 name="Syntax">Syntax</h2>
<p><code><em>array</em>.map(<em>callback</em>[, <em>thisObject</em>])</code></p>
<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 other implementations of the standard. 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 specified in ECMA-262, 5th edition, assuming <code style="color: inherit; font-weight: inherit; ">Object</code>, <code style="color: inherit; font-weight: inherit; ">TypeError</code>, and <code>Array</code> have their original values and that <code style="color: inherit; font-weight: inherit; ">fun.call</code> evaluates to the original value of <code style="color: inherit; font-weight: inherit; "><a href="/en/JavaScript/Reference/Global_Objects/Function/call" rel="internal" style="text-decoration: none; color: rgb(4, 121, 167); ">Function.prototype.call</a></code>.  {{ var DO_NOT_MODIFY_THE_FOLLOWING_CODE_IN_ANY_WAY = 0; }}</p>
<pre class="brush: js">if (!Array.prototype.map) {
  Array.prototype.map = function(fun /*, thisArg */) {
    "use strict";

    if (this == null)
      throw new TypeError('can not convert ' + this + ' to object');

    var t = Object(this);
    var len = t.length &gt;&gt;&gt; 0;
    if (typeof fun != 'function')
      throw new TypeError(fun + ' is not callable');
    
    var result = new Array(len);
    var thisArg = arguments[1];
    for (var i = 0; i &lt; len; i++) {
      if (i in t)
        result[i] = fun.call(thisArg, t[i], i, t);
    }

    return result;
  };
}
</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="brush: js">function fuzzyPlural(single) {
  return single.replace(/o/g, 'e');
}

var words = ["foot", "goose", "moose"];
console.log(words.map(fuzzyPlural));
</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="brush: js">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="brush: js">var map = Array.prototype.map
var a = 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><h3>Browser compatibility</h3>
<p>Based on <a class=" external" href="http://kangax.github.com/es5-compat-table/">Kangax's compat tables</a></p>
<p>{{ CompatibilityTable() }}</p>
<div id="compat-desktop">
<table class="compat-table"> <tbody> <tr> <th>Feature</th> <th>Firefox (Gecko)</th> <th>Chrome</th> <th>Internet Explorer</th> <th>Opera</th> <th>Safari</th> </tr> <tr> <td>Basic support</td> <td>{{ CompatVersionUnknown() }}</td> <td>{{ CompatVersionUnknown() }}</td> <td>9</td> <td>{{ CompatVersionUnknown() }}</td> <td>{{ CompatVersionUnknown() }}</td> </tr> </tbody>
</table>
</div>
<div id="compat-mobile">
<table class="compat-table"> <tbody> <tr> <th>Feature</th> <th>Firefox Mobile (Gecko)</th> <th>Android</th> <th>IE Mobile</th> <th>Opera Mobile</th> <th>Safari Mobile</th> </tr> <tr> <td>Basic support</td> <td>{{ CompatUnknown() }}</td> <td>{{ CompatUnknown() }}</td> <td>{{ CompatUnknown() }}</td> <td>{{ CompatUnknown() }}</td> <td>{{ CompatUnknown() }}</td> </tr> </tbody>
</table>
</div>
<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