Reputation:
I am trying to mimic array.map()
using forEach().
var map = function () {
var empMap = [];
numbers.forEach(function (number) {
empMap.push(number);
console.log('empMap', empMap);
});
return(empMap);
}
var numbers = [1, 2, 3];
//implement this line
var doubles = map(numbers, function (number) {
return number * 2;
});
console.log(doubles); // [2, 4, 6]
So, I have this numbers
array with values and I have my own map function
to iterate through the array and then I pushing the values in an empty array empMap
later, I am calling this map function and multiplying each value with 2 and printing it out.
I should get the output of doubles as [2, 4, 6] instead I am getting [1,2,3]. Not sure where I going wrong.
This is the [codepen]1 for the same.
Upvotes: 0
Views: 203
Reputation: 22939
You need to pass the array and the callback as arguments and then actually use the callback.
var map = function (array, callback) {
var empMap = [];
array.forEach(function (number) {
empMap.push(callback(number))
});
return(empMap);
}
var numbers = [1, 2, 3];
var doubles = map(numbers, function (number) {
return number * 2;
});
console.log(doubles); // [2, 4, 6]
Upvotes: 4