Skip to content

JavaScript map() function | Basics

  • by

If you want to create a new Array from an existing array then use the JavaScript map() function. It creates a new array by calling a function for every array element.

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

Note: it does not change the original array.

JavaScript map() function

A simple example code returns a new array multiply all the values in an array by 2. The Array.map() method allows you to iterate over an array and modify its elements using a callback function.

<!DOCTYPE html>
<html>
<body>

  <script>
    const array1 = [1, 4, 9, 16];

    // pass a function to map
    const map1 = array1.map(x => x * 2);

    console.log(map1);
</script>

</body>
</html> 

Output:

JavaScript map() function

How to use map() over an array of objects?

Answer: You can use the map() method to iterate over the array and join the values of  firstName and lastName as follows:

let users = [
  {firstName : "Susan", lastName: "Steward"},
  {firstName : "Daniel", lastName: "Longbottom"},
  {firstName : "Jacob", lastName: "Black"}
];

let userFullnames = users.map(function(element){
    return `${element.firstName} ${element.lastName}`;
})

console.log(userFullnames);

Output: [“Susan Steward”, “Daniel Longbottom”, “Jacob Black”]

Do comment if you have any doubts or suggestions on this JS basic function.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Tags:

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading