1

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?

  • 5
    You have to run all callbacks against all elements. I'm not sure how you expect to do less of this. – VLAZ Oct 16 '20 at 17:47
  • 2
    What do you mean by "simplify?" What's wrong with what you have now? – General Grievance Oct 16 '20 at 17:49
  • 2
    At any rate, if you want to do "a bunch of actions* against all elements, I'd suggest looking at transducers - constructs that deal with this. See: [How to chain map and filter functions in the correct order](https://stackoverflow.com/q/44198833) | [Transducer flatten and uniq](https://stackoverflow.com/q/52008364) | [Mapping an object to array of objects in ES6](https://stackoverflow.com/q/44015014) – VLAZ Oct 16 '20 at 17:54

1 Answers1

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392