Hi!
So I came across this problem.
I have an array of N elements. I'd like to run every element against a function.
so I would go:
myArray.forEach(item=>process(item)
Now I want to filter some of them and call another function on the rest of them.
.forEach(item=>process(item)
.filter( somelogic )
.forEach( item=>postProcessSome(item) );
But that's not valid code. forEach returns undefined so I can't call filter. I can use map instead of forEach but that way I can't use one liners.
What's an elegant way to do this? For example in Java I could use .peek that acts like a foreach but returns the value.
Thanks for help.
Top comments (9)
.map
is the only option here. If the problem isprocess
return value you can do this.If
process
doesn't mutateitem
that should be fine. You could even make a helper function.Comma operator for implied return from arrow function is kinda gnarly... though I guess that's a matter of personal style preference.
TIL comma operator! Thanks!
What's wrong with this? Easy to reason about and the same total number of lines, though line count is a bit of an artificial metric - better to prioritize readability.
For readability this is definitely the winner and it only iterates over the array once.
Use .map()
This won't work unless
process(item)
returnsitem
.You can even use a simple reduce
Nice! Very cool utilization of reduce I like it.