Stop filter().map()ping arrays

Josh Frank
2 min readSep 14, 2021

Let’s say you have an array of props and you’d like to map only some of them to DOM nodes based on an attribute:

const stories = props.stories.filter( story => story.category !== "wealth_management" ).map( story => <StoryCard story={ story } key={ story.id } /> } );

Avoid chaining iterating functions

This is way up there on my list of coding pet peeves. Let’s turn this ugly stepchild into the belle of the ball and use reduce() instead:

const stories = props.stories.reduce( ( result, story ) => story.category === "wealth_management" ? result : [ <StoryCard story={ story } key={ story.id }/>, ...result ], [] );

A few reasons why:

  • Chaining iterators is bad for performance: This very smart engineer saves me the trouble of writing an explain-er-y blog post proving it (as much as I love doing that), so you don’t have to take my word for it. Sure, the performance difference is trivial, exceedingly so in most cases… but it’s not zero, and more importantly…
  • Chaining iterators is clunky and unreadable: reduce() is one of JavaScript’s most powerful tools, yet it remains shamefully underused and poorly understood. To any complainers, I say: change your diapers — are you a hacker or not? Seriously, reduce() was introduced in 2011! It’s now JavaScript 101 and in 2021 there’s no excuse for whining about reduce because…
  • Chaining iterators is repetitive and lazy: No serious programmer chains array iterators like this —that’s like how a medieval farmer would code. Anyone who considers filter().map() more readable than reduce in the example above deserves a court-martial.

--

--

Josh Frank

Oh geez, Josh Frank decided to go to Flatiron? He must be insane…