0

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.

Nauman
  • 894
  • 4
  • 14
  • 45

1 Answers1

5

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]
nicholaswmin
  • 21,686
  • 15
  • 91
  • 167
  • Minor quibble - you're using the name `numbers` twice in the same scope, would be better to change one of them to avoid shadowing. – Duncan Thacker Jan 30 '19 at 14:03
  • 1
    I intentionally avoid changing the OP as much as possible, instead opting to only tweak what's necessary. OP should [take a note](https://stackoverflow.com/questions/11901427/an-example-of-variable-shadowing-in-javascript) of your comment though. – nicholaswmin Jan 30 '19 at 14:03