Array map() Method - Javascript Array

Javascript examples for Array:map

Description

The map() method creates a new array with the results of calling a function for every array element.

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.
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
thisValue Optional. A value to be passed to the function to be used as its "this" value.

Return Value:

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

The following code shows how to use the map function:

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<body>

<button onclick="myFunction()">Test</button>

<p>New array: <span id="demo"></span></p>

<script>
var persons = [/*from ww w. ja  va2  s.c om*/
    {firstname : "A", lastname: "R"},
    {firstname : "K", lastname: "F"},
    {firstname : "J", lastname: "C"}
];


function getFullName(item,index) {
    var fullname = [item.firstname,item.lastname].join(" ");
    return fullname;
}

function myFunction() {
    document.getElementById("demo").innerHTML = persons.map(getFullName);
}
</script>

</body>
</html>

Related Tutorials