Knowing when to use Map, Filter, and Reduce + ES6

Gage Thornberry
3 min readJul 25, 2020
Amazing example

Introduction

JavaScript, previously known as Mocha, was developed in 1995 by a guy named Brendan Eich. During this time Eich was working as a Netscape Communications Corporation programmer, and he used his free time outside of work to put the scripting language together.

In 1995 there were two dominating web browsers: Netscape Navigator and Internet explorer. When JS hit the market in 1996 it became massively popular for it’s ability to support Java in the browser (hint the name JavaScript).

Fast forward 25 years and statistics show that 92% of websites that are created use Javascript somewhere in the stack. One reason that Javascript has held together so tightly throughout the years is all of the consistent hard work that gets put in to update, fix, and optimize the language for maximum capability within web development.

One type of method that you will find in most object oriented programming languages are array methods.

Javascript’s most common array methods are Map, Filter, and Reduce.

Map — The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

Filter — The filter() method creates a new array with all elements that pass the test implemented by the provided function.

Reduce — The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in single output value.

When to use them?

Map is most commonly used when you want to do something to one or every item in an array, and return a new array of the same length. If the solution to the problem involves returning a new array that is the same size, that’s a good indicator of when you should probably use map.

Filter should be used when you want to look into an array and pull out certain items that match the condition that you set. Filter returns a new array where size doesn’t exactly correlate. If nothing matches the condition in a filter method, an empty array will be returned.

Reduce is most commonly used when you want to add, subtract, multiply etc. multiple items in an array and return a single value. Reduce takes 4 different arguments accumulator (acc), Current (cur), Current index (idx), and Source array (src).

The reduce method works by executing the function that you pass to the reduce method on each element in the array. This can be done by passing the function right into to reduce method, or by creating a separate function that would be called in the reduce method.

example -

Separate methods
Passing function directly into reduce method

That’s pretty much the basics! I hope after reading this that it’s a little more clear when to use Map, Filter, and Reduce. Thanks for reading!

--

--