Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using javascript map with a function that has two arguments

Tags:

javascript

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.

like image 941
Curious2learn Avatar asked Sep 10 '12 00:09

Curious2learn


People also ask

Can map take multiple arguments?

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.

How many arguments can be passed to map () function?

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.


4 Answers

Use an anonymous function:

values.map(
  function(x) { return squarefuncwithadjustment(x, 2); }
);
like image 199
casablanca Avatar answered Oct 24 '22 12:10

casablanca


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]
like image 23
Peter Avatar answered Oct 24 '22 11:10

Peter


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))
like image 35
Dima Vinogradov Avatar answered Oct 24 '22 12:10

Dima Vinogradov


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]
like image 9
gray state is coming Avatar answered Oct 24 '22 12:10

gray state is coming