I know that I can use map
with a function of one variable in the following manner:
var squarefunc = function(x) {
return x*x;
};
values = [1,2,3,4]
values.map(squarefunc) // returns [1,4,9,16]
How do I use map
with the following function:
var squarefuncwithadjustment = function(x, adjustment) {
return (x*x + adjustment);
}
where, I want to input value for argument adjustment
manually when I call map, say adjustment=2
, and have the value of x
taken from the array values
.
Using the Python map() function with multiple arguments functions. Besides using the Python map() function to apply single argument functions to an iterable, we can use it to apply functions with multiple arguments.
The map function has two arguments (1) a function, and (2) an iterable. Applies the function to each element of the iterable and returns a map object.
Use an anonymous function:
values.map(
function(x) { return squarefuncwithadjustment(x, 2); }
);
You could use a callback creation function:
var createSquareFuncWithAdjustment = function(adjustment) {
return function(x) { return (x * x) + adjustment; };
};
values = [1, 2, 3, 4];
values.map(createSquareFuncWithAdjustment(2)); // returns [3, 6, 11, 18]
As of ES6 you can use:
.map(element => fn(element, params))
In your case if I want to use 3 as adjustment:
values = [1,2,3,4]
values.map(n => squarefuncwithadjustment(n, 3))
If you reverse the order of your arguments, you can bind the adjustment as the first argument, so that the x
will be passed as the second.
var squarefuncwithadjustment = function(adjustment, x) {
return (x*x + adjustment);
}
values.map(squarefuncwithadjustment.bind(null, 2)); // [3, 6, 11, 18]
The first argument to .bind
sets the calling context, which doesn't matter here, so I used null
. The second argument to .bind
binds 2
as the first argument when invoked.
It may be better to store the function as a bound version.
var squareFuncWith2 = squarefuncwithadjustment.bind(null, 2);
Then use it with .map
.
values.map(squareFuncWith2); // [3, 6, 11, 18]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With