Stop filter().map()ping arrays

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.

--

--

--

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

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Notes from Kent Dodds 3-minute podcasts

10 Popular Svelte UI Components

How we added an animated Splash Screen to our React Native app

React.js tips for better performance. Part 1

Deploy Your Angular App to Netlify In Minutes

What gets logged in the console when you’re mutating objects

Automated data driven with Postman

Understand Async and Defer with example.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Josh Frank

Josh Frank

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

More from Medium

Async Redux — How to use Thunk Middleware

Need a refresher on functions in JavaScript? Here is a quick overview

What the hell is a sparse array (in JavaScript) and why might it matter?

React: Controlled vs. Uncontrolled