To create a function by mapping an array in JavaScript, follow these steps:
map()
method to iterate over each value in the array and apply the function logic to it.Here is an example code:
//Step 1: Create an array
let numbers = [1, 2, 3, 4, 5];
//Step 2: Declare a function
function multiplyByTwo(arr) {
//Step 3: Use map() to iterate over the array and apply logic
let updatedArray = arr.map(function(num) {
return num * 2;
});
//Step 4: Return updated array
return updatedArray;
}
console.log(multiplyByTwo(numbers)); //Output: [2, 4, 6, 8, 10]
This is just an example, you can modify the logic accordingly to suit your requirements.
Asked: 2021-11-27 11:00:00 +0000
Seen: 7 times
Last updated: Aug 18 '21