How to Pass Parameter to array.map()?
You're looking for partial application. It can be done with bind
for example (or a number of helper functions that come with functional libraries, like in Underscore):
arr.map(multiplyBy.bind(null, 4))
however a simple arrow function would be easier:
arr.map(x => multiplyBy(4, x))
But you can also get the partial application for free if you curry your multiplyBy
function, taking the multiplier and returning a new function:
function multiplyBy(multiplier) {
return function(num) {
return num * multiplier;
};
}
// ES6 arrow functions:
const multiplyBy = multiplier => num => num * multiplier;
arr.map(multiplyBy(4));
You can do something called a factory currying. Effectively, you make a function that will return another function which is tailored to your needs. In this case, an anonymous one.
var arr = [1, 2, 3, 4, 5];
function multiplyBy(scale) {
return function(num){
return num * scale;
}
}
console.log( arr.map( multiplyBy(4) ));
This works because the scope of the anonymous function that is returned is within that of the factory outer function. So, whenever we produce a new function, it will retain the value of scale
that was given for its production.
Edit: The last part of @Bergi 's answer is the same as mine. The concept is apparently called currying. Thanks @Bergi ! The Factory pattern is more often applied to the production of objects, as Bergi noted, but it was the only thing I could think of at the time, and javascript sort of treats functions like objects. In this specific case, they are effectively similar. Here is a good reference for currying in JavaScript
You can use Function.prototype.bind
to create a new function with bound arguments. For example
var arr = [1, 2, 3, 4, 5];
function multiplyBy(multiplyBy, num) {
// note the "num" argument must come last if it is to represent the argument from "map"
return num * multiplyBy;
}
console.log( arr.map(multiplyBy.bind(null, 4)) ); // null is for the "this" argument