JavaScript Array map() Method - GeeksforGeeks

JavaScript Array map() Method

Last Updated : 31 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The JavaScript map() method is very important for working with arrays, allowing you to iterate over each element and apply a specified callback function. This method creates a new array by transforming each element based on the logic defined within the callback function. Crucially, the original array remains unchanged, maintaining its integrity throughout the process.

One notable feature of the `map()` method is its handling of empty elements. It automatically skips executing the callback function for these elements, focusing solely on processing non-empty values. This behavior ensures efficient and streamlined processing, enhancing the overall performance of array transformations.

Syntax:

map((element, index, array) => { /* … */ })

Parameters:

  • element: It is a required parameter and it holds the value of the current element.
  • index: It is an optional parameter and it holds the index of the current element.
  • arr: It is an optional parameter and it holds the array.

Return Value:

It returns a new array and elements of arrays are the result of the callback function. 

Example:

Here, we are using the map() method to create a new array containing the square roots of each number in the original array.

Javascript
const numbers = [1, 4, 9, 16, 25];
const squareRoots = numbers.map(num => Math.sqrt(num));

console.log(squareRoots); // Output: [1, 2, 3, 4, 5]

Output
[ 1, 2, 3, 4, 5 ]

Explanation:

  • The code uses the map() method to iterate over an array of numbers.
  • For each number in the array, it applies an arrow function to calculate its square root.
  • The map() method returns a new array containing the square roots.
  • The resulting array of square roots is logged to the console.

JavaScript Array map() Method Example

This example uses the array map() method and returns the square of the array element. 

Javascript
// Input array
let arr = [2, 5, 6, 3, 8, 9];

// Using map to transform elements
let newArr = arr.map(function (val, index) {
    return { key: index, value: val * val };
})

// Display output
console.log(newArr)

Output
[
  { key: 0, value: 4 },
  { key: 1, value: 25 },
  { key: 2, value: 36 },
  { key: 3, value: 9 },
  { key: 4, value: 64 },
  { key: 5, value: 81 }
]

Explanation:

  • Input array arr contains numbers.
  • map() iterates over each element, executing a callback function.
  • Callback returns objects with index-value pairs representing squares of elements.
  • New array newArr holds transformed elements.
  • Result is logged, showing index-value pairs of squared elements.

JavaScript Array map() Method Example:

This example uses the array map() method to concatenate the character ‘A’ with every character of the name. 

Javascript
//Input string
let name = "Geeks";

// New array of character and names
// concatenated with 'A'
let newName = Array.prototype.map.call(name, function (item) {
    return item + 'A';
})

// Display output
console.log(newName)

Output
[ 'GA', 'eA', 'eA', 'kA', 'sA' ]

Explanation:

Here,

  • Input string name is “Geeks”.
  • map() is invoked on name string using Array.prototype.map.call().
  • Callback appends ‘A’ to each character.
  • Transformed elements stored in new array newName.
  • Result logged, showing characters of original string concatenated with ‘A’.

Using a callback function with an argument

Using parseInt() with map() method. The parseInt() function converts strings to integers. When used with map(), it converts each element of an array of strings to integers.

JavaScript parseInt() with map() Example:

Here, we are using parseint with map().

Javascript
const strings = ['10', '20', '30'];
const integers = strings.map(str => parseInt(str));

console.log(integers); // Output: [10, 20, 30]

Output
[ 10, 20, 30 ]

Explanation:

The code uses map() to iterate over an array of strings. For each string, parseInt() converts it to an integer. The resulting integers are stored in a new array. Finally, the new array containing integers is logged to the console.

We have a complete list of Javascript Array methods, to check those please go through this Javascript Array Complete reference article.

We have a Cheat Sheet on Javascript where we covered all the important topics of Javascript to check those please go through Javascript Cheat Sheet-A Basic guide to JavaScript

JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.



Previous Article
Next Article

Similar Reads

How to map array values without using map method in JavaScript ?
Array elements can be mapped by using looping methods in JavaScript. The map() method creates a new array with the results of the output of a function called for each array element. This can also be implemented using for loop in JavaScript. Approach: For this, we can create two arrays, in which one array contains the array elements that are to be m
2 min read
PHP | Ds\Map map() Function
The Ds\Map::map() function of the Map class in PHP is used to apply a callback function to a Map object. This returns the result of applying the callback function to each value present on the map. The function does not update the values in the original map, instead, it just returns the result of the updates without affecting the original values. Sy
2 min read
What is image map & how to map the image in HTML ?
In this article, we will discuss an image map in HTML, along with understanding its implementation through the examples. An Image Map refers to the clickable image having a clickable area that can be used to navigate to the various link to other web pages or the specific section of the same web page. The <map> tag can be used to define the im
2 min read
Create a Map with Google Map Api using React-Native
In this project, we'll explore how to integrate Google Maps into a React Native application. We'll create a dynamic map that allows users to view their current location and interact with markers on the map. This project aims to provide a practical guide for developers looking to incorporate maps into their mobile applications using React Native. Ou
3 min read
Implement polyfill for Array.prototype.map() method in JavaScript
In this article, we will learn how to implement a polyfill for an Array.prototype.map() method in JavaScript. What is a polyfill? A polyfill is a piece of computer code written to implement a feature in a browser that does not yet support it. It could be because of the older version of the browser you are using, or because the new version of the br
3 min read
How to Convert Array into Array of Objects using map() & reduce() in JavaScript?
An array of objects can contain multiple objects with the same properties i.e. key-value pairs. But a map does not contain duplicate values which means if you convert an array of objects with duplicate objects into a map, it will contain only the unique key-value pairs. Below are the approaches to convert an array of objects to a map in JavaScript:
2 min read
JavaScript Map.prototype[@@iterator]() Method
Map[@@iterator]( ) method is used to make Map iterable. Map[@@iterator]( ) method returns iterator object which iterates over all code points of Map. Map[@@iterator]( ) is built-in property of Map. We can use this method by creating Map iterator. We can make Map iterator by calling the @@iterator property. In place of @@iterator, we can use Symbol.
2 min read
JavaScript Map has() Method
The Map.has() method in Javascript is used to check whether an element with a specified key exists in a map or not. It returns a boolean value indicating the presence or absence of an element with a specified key in a map. The Map.has() method takes the key of the element to be searched as an argument and returns a boolean value. It returns true if
2 min read
JavaScript Map clear() Method
JavaScript Map.clear() method is used for the removal of all the elements from a map and making it empty. It removes all the [key, value] from the map. No arguments are required to be sent as parameters to the Map.clear() method and it returns an undefined return value. Syntax: mapObj.clear() Parameters: No parameters are required in the Map.clear(
2 min read
JavaScript Map get() Method
The Map.get() method in JavaScript is used for returning a specific element among all the elements which are present in a map. The Map.get() method takes the key of the element to be returned as an argument and returns the element which is associated with the specified key passed as an argument. If the key passed as an argument is not present in th
3 min read