React, etc. Tech Stack

React, Flux, GraphQL, Hack, HHVM...? All of this and more!

Introduction to Map, Filter and Reduce in JavaScript

A wave of functional programming is washing over the JavaScript ecosystem. This has made the development world polluted with terms that might sound alien to majority of developers used to programming with a bunch of loops with ifs and elses.

In reality many of these concepts are not that difficult and are just another way of accomplishing what you have done in the past with loops and if and elses. These can be useful tools to write maintainable code, but can be intimidating terms if you take them for something more than they're worth.

Often you have actually used the same exact functional programming concepts without actually knowing that they are. Here are three terms explained that you have probably heard when working with some of the JavaScript with an academic feel to it:

If you've got business logic that's got a thousand of ifs and elses, then any magical functional programming logic will not make those if-elses go away. It can simplify how the code looks, but the logic will be somewhere.

Below are very basic samples of Map, Filter and Reduce in action, they can (and are) used in more complex ways, but the basic mechanism remains the same.

Map in JavaScript

Map essentially takes an array, loops it over and returns a set changed values. This is done using a function, so instead for writing a loop, you can use Map to apply a function to each element in an array.

Consider the example below, this uses Map to apply the uppercasing function to an array to create a new array:

Filter in JavaScript

Filter is used to remove items from an array that should not be there. This is done with any evaluation which will return true for something that should be returned and false (or nothing) for items that should not be returned.

 Based on the example with the names above, we will use Filter to create a new array with only names that contain the letter "e" in them:

Reduce in JavaScript

Reduce is used to flatten structures to something final. It is essentially a loop that is also aware of the result of the previous step in the cycle. In a simple example you could use to sum all the ages in an array together:

A good place to learn more about these is the Mozilla Developer Network:

Written by Jorgé on Wednesday August 3, 2016

Permalink -

« Popular WordPress plugin allows authenticated users to execute any PHP on page load - A static site generator built with React: Antwar »