I have defined my own map function, which serves the same purpose as the method on Array objects. (I am doing this to learn). The code is below.
I would like to use Array's forEach method inside of my own definition of map, but I am missing something conceptually. How would I be able to do this using forEach?
Working without using forEach
// transforming with map
// NOTE: map is already defined in JavaScript
function map(array, transformation) {
var mapped = [];
for (var index in array) {
var currentElement = array[index];
var transformedElement = transformation(currentElement);
mapped.push(transformedElement);
}
return mapped;
}
My Attempt of using forEach
function mapForEach(array, transformation) {
var mapped = [];
array.forEach(transformation(currentVal, index, array, mapped));
return mapped;
}
function transformation(person, index, array, accumulator) {
var name = person.name;
accumulator.push(name);
}