0

I'd like to simplify my nested foreach inside a map in javascript, but was not sure how to approach it

this is what I have:

var items = [1, 2, 3];
var callbacks = [function() { console.log('hi') }, function() { console.log('hi') }]

var result = items.map(item => {
  var intermediate = item;
  callbacks.forEach(callback => {
    intermediate = callback(intermediate);
  })
  return intermediate;
});
console.log(result);

are you able to help pls?

3

1 Answer 1

2

You could reduce the arrays with the callbacks and map the values.

const
    items = [1, 2, 3],
    callbacks = [x => x + 1, x => 2 * x],
    result = items.map(item => callbacks.reduce((x, fn) => fn(x), item));

console.log(result);

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

Comments

Your Answer

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