Javascript - Array map() Method

The map() method returns a new array with the elements being processed by a function for every array element.

Description

The map() method returns a new array with the elements being processed by a function for every array element.

The map() method calls the function once for each element in an array.

Array map() method does not run the function for array elements without values.

And it does not change the original array.

Syntax

array.map(function(currentValue, index, arr), thisValue)

Parameter Values

Parameter Require Description
function(currentValue, index, arr) Required. A function to be run for each element in the array.
thisValue Optional. A value to be passed to the function as its "this" value. If this parameter is empty, the value "undefined" is used
Argument Require Description
currentValue Required. The value of the current element
index Optional. The array index of the current element
arrOptional. The array object the current element belongs to

Return

An Array containing the results of calling the provided function for each element in the original array.

Example

Return an array with the square root of all the values in the original array:

Demo

var numbers = [4, 9, 16, 25];

console.log(numbers.map(Math.sqrt));

//Multiply all the values in array with a specific number:

var numbers = [5, 4, 2, 3];

function multiplyArrayElement(num) {
    return num * 5;
}

console.log( numbers.map(multiplyArrayElement));

//Get the full name for each person in the array:

var persons = [// w ww.  ja v  a 2 s.  c om
    {firstname : "M", lastname: "R"},
    {firstname : "K", lastname: "F"},
    {firstname : "J", lastname: "C"}
];
function getFullName(item,index) {
    var fullname = [item.firstname,item.lastname].join(" ");
    return fullname;
}

console.log( persons.map(getFullName));

Result