0

For example, I have an array of functions: [func1, func2, func3, func4] and array of arguments [arg1, arg2, arg3, arg4]. I need to apply func1 to arg1, func2 to arg2 etc.

What is the best way to do this? Of course, I can use simple loop to go through elements, but maybe more elegant way exists.

3 Answers 3

4

There are a few ways to do it. I'd suggest using the .map() method to iterate over the functions, because then you can easily put their return values into another array:

const results = funcs.map((f, i) => f(args[i]))

In context:

const funcs = [
  (a) => a * 2,
  (a) => a * 3,
  (a) => a * 4,
  (a) => a * 5
]
const args = [1, 2, 3, 4]
const results = funcs.map((f, i) => f(args[i]))

console.log(results)

Sign up to request clarification or add additional context in comments.

Comments

3

I don't know if it's "elegant," but you can do

let results = functionArray.map((f, i) => f(arguments[i]))

This takes each function in your array, finds the associated argument i, and calls the function with that argument.

2 Comments

Well I think it's elegant, but then I came up with an identical solution so I'm biased. (Sorry, normally I would delete my answer upon realising somebody else posted the same thing first, but in this case I didn't notice your answer until after I took the time to add a working demo, so I'll leave you with an upvote instead.)
@nnnnnn No problem! Yours included multiple ways to accomplish it!
1

If you use a library like Lodash, you can use _.zipWith, which iterates several arrays at once all in parallel, calling the provided function with the elements of the arrays.

const results = _.zipWith(funcs, args, (f, a) => f(a));

If you want a simple implementation of zipWith without importing the library, use:

const zipWith = (...arrays) => {
  const func = arrays.pop();
  return arrays[0].map((_, i) => func(...arrays.map(arr => arr[i])));
};

const zipWith = (...arrays) => {
  const func = arrays.pop();
  return arrays[0].map((_, i) => func(...arrays.map(arr => arr[i])));
};

const funcs = [
  a => a * 2,
  a => a * 3,
  a => a * 4,
  a => a * 5
];
const args = [1, 2, 3, 4];

console.log(zipWith(funcs, args, (f, a) => f(a)));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.