Write a function that takes an array of numbers and a function as parameters. The function parameter should do something to a numbers (increment, double, decrement, etc) and return the result. Your function should return the array that results from applying the function parameter to each element in the number arrav.
const map = (array, func) => {
const newArray = [];
array.forEach((num) => {
const output = func(num);
newArray.push(output);
});
return newArray;
}
const newArray = [];
The forEach() method iterates over each item in the array and executes a provided function once for each element.
array.forEach((num) => {
And then for each number in the array, we want to get the output of calling func
and passing in num
.
const output = func(num);
Now push that output into our new array (NOTE: the push
method adds one or more elements to the end of an array and returns the new length of the array.
newArray.push(output);
});
console.log(newArray);
return newArray;
}
map([1,2,8], function(num){return num/2})