Level Up Your JavaScript Arrays With These Four Building-Block Functions

Using Map, Reduce, Filter, and Find, you can write better JavaScript code.

Cameron Manavian
Level Up Coding
Published in
4 min readSep 2, 2020

--

Photo by James Pond on Unsplash

Arrays in JavaScript are something special, as they leverage the prototype feature of JS and provide a handy way to run functions directly from a reference to an array instance.

I believe that using these four functions as much as possible within your code will not only make you more efficient, but also make you more popular on your team and generally more amazing at what you do.

All four of these prototype functions accept a “callback” function, which is a pure function that accepts arguments and must return something expected back to the caller, whether it be a boolean liketrue or false, or a type like String, Object, Array, or Number.

Let’s take a look at each of these useful Array functions and learn to make our code more concise!

Map — Array.prototype.map()

Photo by Louis Hansel @shotsoflouis on Unsplash

map is a building block of most programming languages, and is definitely a wonderful Array function to start with.

This line of code for instance, will loop through ANIMALS and create an array of Strings, with their name and animal type:

You might already be familiar with map if you are using front-end frameworks like React or Vue where you quite often need to loop through an array of data to produce HTML:

<ul>
{ANIMALS.map((animal) =>
<li>
{animal.name} ({animal.type})
</li>
)}
</ul>

// produces:
<ul>
<li>Spot (dog)</li>
<li>Fluffy (cat)</li>
<li>Peppy (bird)</li>
<li>Lizzy (lizard)</li>
</ul>

The map function is all-around useful to convert array of something X into array of something Y.

--

--