;

Javascript Array - map() Method


Tutorialsrack 15/10/2022 Jquery Javascript

In this article, you will learn about the javascript Array built-in method Array.prototype.map(). How does this method work in javascript? 

Array.prototype.map()

This Array.prototype.map() method invokes a callback function for each element in the calling array. And returns the new array. 

Syntax
array.map(callback(element [, index [, array]]) [,thisParameter]);

This method takes 2 parameters as given below:

  • callback: This parameter holds the function to be called for each element of the array. Each time the callback function executes, the returned value is added to the newArray. This function takes the mentioned parameters below:
    • element: This parameter holds the current element of the array.
    • Index(Optional): This parameter holds the index of the current element within the array.
    • array(Optional): This parameter holds the reference to the original array.
  • thisParameter(Optional): This parameter holds the context to be passed as this to be used while executing the callback function.

The map() does not change the original array. And it executes a callback once for each array element in order.

The map() does not execute the callback function for an array of empty elements.

Here are some examples of the Array.prototype.map() method:

Examples
const numbers = [4, 9, 16, 25, 36];
const newArr = numbers.map(Math.sqrt)

console.log(newArr);
// Output => [2, 3, 4, 5, 6]


//Multiply all the values by 10
const newArr1 = numbers.map(myFunction)

function myFunction(num) {
  return num * 10;
}

console.log(newArr1)
//Output => [40, 90, 160, 250, 360]

//Reformat the array
const keyValueArray = [
  { key: 1, value: 40 },
  { key: 2, value: 60 },
  { key: 3, value: 80 },
];

const reformattedArray = keyValueArray.map(({ key, value}) => ({ [key]: value }));

console.log(reformattedArray);
// reformattedArray is now [{1: 10}, {2: 20}, {3: 30}],


//Sparse Array
const sparseArray = [4, , 16, , 36];

console.log(sparseArray.map(item=>item));
//Output => [4, empty, 16, empty, 36]

I hope this article will help you to understand the javascript Array built-in method Array.prototype.map()

Share your valuable feedback, please post your comment at the bottom of this article. Thank you!


Related Posts



Comments

Recent Posts
Tags