JS callback using map() with a function that has one additional parameter

arrays, callback, dictionary, javascript, parameters

Solution

Use an anonymous function:

A.map(function(a) {return doOpSingle2(a,theFlag);});

Problem

I'm trying to find a way to use JS's `Array.prototype.map()` functionality with a function that has one additional parameter more (if possible at all, and I'd like to avoid having to rewrite built-in `Array.prototype.map()`). This documentation is very good, but does not cover the "one-or-more-additional-parameter" case: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/map ``` function doOpSingle(elem) { // do something with one array element } var A = ["one", "two", "three", "four"]; var x = A.map(doOpSingle); // this will execute doOpSingle() on each array element ``` So far, so good. But what if the function in question has two parameters, like e. g. a flag you might want to OR to it (think of bit masks) ``` function doOpSingle2(arrelem,flag) { // do something with one array element } var A = ["one", "two", "three", "four"]; var theFlag = util.getMask(); // call external function var y = A.map(doOpSingle2(theFlag)); // this does not work! ``` Any solutions should do without `for` loops, of course, because that's why we have `map()`, to make our code cleaner w/getting rid of these!

Original source

Related problems