JavaScript Array map() Method
Example
Return an array with the square root of all the values in the original array:
var numbers = [4, 9, 16, 25];
function myFunction() {
x = document.getElementById("demo")
x.innerHTML = numbers.map(Math.sqrt);
}
Try it Yourself »
More "Try it Yourself" examples below.
Definition and Usage
The map() method creates a new array with the results of calling a function for every array element.
The map() method calls the provided function once for each element in an array, in order.
Note: map() does not execute the function for array elements without values.
Note: map() does not change the original array.
Browser Support
The numbers in the table specify the first browser version that fully supports the method.
Method | |||||
---|---|---|---|---|---|
map() | Yes | 9.0 | 1.5 | Yes | Yes |
Syntax
array.map(function(currentValue, index, arr), thisValue)
Parameter Values
Parameter | Description | ||||||||
---|---|---|---|---|---|---|---|---|---|
function(currentValue, index, arr) | Required. A function to be run for each element in the array. Function arguments:
|
||||||||
thisValue | Optional. A value to be passed to the function to be used as its "this" value. If this parameter is empty, the value "undefined" will be passed as its "this" value |
Technical Details
Return Value: | An Array containing the results of calling the provided function for each element in the original array. |
---|---|
JavaScript Version: | ECMAScript 5 |
More Examples
Example
Multiply all the values in array with a specific number:
var numbers = [65, 44, 12, 4];
function multiplyArrayElement(num) {
return num * document.getElementById("multiplyWith").value;
}
function myFunction() {
document.getElementById("demo").innerHTML = numbers.map(multiplyArrayElement);
}
Try it Yourself »
Example
Get the full name for each person in the array:
var persons = [
{firstname : "Malcom", lastname: "Reynolds"},
{firstname : "Kaylee", lastname: "Frye"},
{firstname : "Jayne", lastname: "Cobb"}
];
function getFullName(item, index) {
var fullname = [item.firstname,item.lastname].join(" ");
return fullname;
}
function myFunction() {
document.getElementById("demo").innerHTML = persons.map(getFullName);
}
Try it Yourself »
❮ JavaScript Array Reference