Skip to content Skip to sidebar Skip to footer

How To Define Map In Terms Of Foreach

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 forEac

Solution 1:

The missing concept here is pass by value. The changes to accumulator will not be reflected in forEach. forEach is not actually designed to return a value for each iteration. For that you have map.

Taken from here,

foreach iterates over a list and applies some operation with side effects to each list member (such as saving each one to the database for example)

map iterates over a list, transforms each member of that list, and returns another list of the same size with the transformed members (such as converting a list of strings to uppercase)

Try this code:

functionmapForEach(array, transformation) {
    var mapped = array.map(transformation);
    return mapped; 
}

functiontransformation(person, index, array) {
    var name = person.name;
    return name; 
}

Here is a JSFiddle

If you absolutely have to use forEach, then rather than passing a value, a global variable has to be used. This would be then

var accumulator =[];

functionmapForEach(array, transformation) {
    array.forEach(transformation);
    return accumulator;
}

functiontransformation(person, index, array) {
    var name = person.name;
    accumulator.push(name);
}

JSFiddle - forEach

Solution 2:

You're almost right with your method, but like @Katana314 says, you need to bind, not call. Here's how I would do it:

functionmap(array,mapper) {
    var ret=[];
    array.forEach((val,key)=>{
        //Since arrays are supposed to be sequential, we don't have to worry//about keys matching, if they don't match, the user/developer did//something horribly wrong.
        ret.push(mapper(val,key,array));
    });
    return ret;
}

And here's how I would fix your way.

functionmapForEach(array, func) {
    var mapped = [];
    array.forEach(mapForEachPusher.bind(null,mapped,func));
    return mapped;
}
functionmapForEachPusher(mapped,func,value,index,array) {
    mapped.push(func(value,index,array));
}

functionextract_name(person) {
    return person.name;
}
mapForEach(
    [{name:'Billy'},{name:'Bob'},{name:'Bridget'},{name:'Brittany'},{name:'"B word"'}]
    ,extract_name
);
//["Billy", "Bob", "Bridget", "Brittany", "\"B word\""]

It's effectively the same thing, your way moves the .push() call out of the main function, which means you have to pass data around, whereas I only need to reference from the outer scope. The only downside to my way is the overhead of the function, but it is an arrow function, so that might make it lightweight enough to not matter.

Post a Comment for "How To Define Map In Terms Of Foreach"