user1506269
user1506269

Reputation:

Simplifying nested loops in javascript

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?

Upvotes: 1

Views: 281

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386560

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);

Upvotes: 2

Related Questions