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

Complete Step-by-Step Firebase Authentication in Angular 2 — Part 2

July 2: Generating k-combinations with recursion in JavaScript

Vaadin 8 and Vue.js — a smooth migration

How to reuse third-party library in SAPUI5 (lodash and moment.js).

From writing Android to React-Native apps

Publish your React app to FREE Firebase Hosting

Spotify Year-In-Review for Google Play Music U

How to Clone Git Repo with ssh url by executing command through java using ProcessBuilder.

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

YAGNI — You ain’t gonna need it

SOLID Principles — Programmers’ Life Saver

Introduction to Functional Programming

How to Receive Webhook Events With Netlify Functions and JavaScript