Apply JavaScript map() to an Array
In this tutorial, we will learn about a built-in function in JavaScript known as map(). It is a high-order function. The map() method returns a new array containing the results of calling a given function on each element of the calling array.
The Array.map() method is commonly used to apply changes to the elements, such as multiplying by a specific number or performing any other operations that your application may require.
The syntax of the map function:
array.map(function(element, index, arr), thisValue)
The map() method passes:
- element: the current element.
- index: index of the current element.
- Arr: passes the array object into the callback function.
- thisValue: It is an optional parameter and holds the value of the function passed, generally it is not defined.
Index and arr are optional parameters.
Return Value: It returns a new array with array elements as the result of the callback function.
Example 1:
Here, you take the array as the input and return the square of each element in that array as the output.
- For loop
let arr1 = [1, 2, 3, 4];
for (let i = 0; i < arr1.length; i++){
arr1[i] = arr1[i] * 2;
}
console.log(arr1);OUTPUT:
[ 2, 4, 6, 8 ]
Instead of looping on the element through each element and then storing it an array, we can use the map function
- Applying
Map()function to an array
let mynum1 = [1, 2, 3, 4];
let try1 =mynum1.map(function(element){
return element *2;
});
console.log(try1);
OUTPUT:
[ 2, 4, 6, 8 ]Example 2:
You can also use Map() function with an array of objects:
It iterates over the array and joins the Name and Type
let brands = [
{Name : "H&M", Type: "Fashion"},
{Name : "Tiffany", Type: "Jewellery"},
{Name : "Rolex", Type: "Watch"}
];
let products = brands.map(function(element){
return `${element.Name} - ${element.Type}`;
})
console.log(products);Output: [ 'H&M - Fashion, 'Tiffany - Jewellery', 'Rolex - Watch' ].
These are some of the ways you can use the Map() function on the array.
Leave a Reply