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?
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.