In this article, you will learn about the javascript Array built-in method Array.prototype.map()
. How does this method work in javascript?
This Array.prototype.map()
method invokes a callback function for each element in the calling array. And returns the new array.
array.map(callback(element [, index [, array]]) [,thisParameter]);
This method takes 2 parameters as given below:
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:
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!
Comments