Sie sind auf Seite 1von 6

Luuk Gruijs

Senior front-end developer writing about Angular and Javascript


Jun 26, 2017 · 4 min read

Understanding map, lter and reduce in Javascript

Photo by Joshua Earle on Unsplash

When working on Javascript projects you inevitably come across situations where you
have to do some data manipulation. You can always use a for-loop to get the desired
result, but for-loops can quickly become a bit messy and large. Most of the times it can
be much easier to use the map , filter or reduce operator. Your code stays cleaner and
is easier to read. At least, if you understand how they work and when you should use
them.

The rule of thumb i use to determine which operator i should use is as follows:

• If i already have an array and i want to do the exact same operation on each of the
elements in the array and return the same amount of items in the array, use the map .

• If i already have an array but i only want to have items in the array that match certain
criteria, use the filter .

• If i already have an array, but i want to use the values in that array to create
something completely new, use the reduce .

These rules might seem a little vague, so let’s dive into some examples. For our examples
we use a small animals array that looks like this:

1 const animals = [
2 {
3 "name": "cat",
4 "size": "small",
5 "weight": 5
6 },
7 {
8 "name": "dog",
9 "size": "small",
10 "weight": 10
11 },
12 {
13 "name": "lion",
14 "size": "medium",
15 "weight": 150
16 },
17 {
18 "name": "elephant",
19 "size": "big",
20 "weight": 5000
21 }
22 ]

data.js hosted with ❤ by G i t H u b view raw

The map operator


Let’s say we want to have an array with just the names of all the animals. Using a for-
loop we would write something like this:

1 let animal_names = [];


2
3 for (let i = 0; i < animals.length; i++) {
4 animal_names.push(animals[i].name);
5 }

for_loop_map.js hosted with ❤ by G i t H u b view raw


Using the map-operator we can write the same like this:

1 let animal_names = animals.map((animal, index, animals) => {


2 return animal.name
3 })

m a p . j s hosted with ❤ by G i t H u b view raw

The map operator accepts three values in the callback function, namely:

• The current item of the array

• The current index of the current item

• The entire array

While this is a very easy example, there are some key improvements in our code
readability when we use the map :

1. Using the map , we don’t have to manage the state of our for-loop.

2. We don’t have to use the index of the for-loop to access the correct item in the array.

3. We don’t have to create a new array and push our values into it. Map returns the
nished array in one go, so we can simply assign it to a variable.

There is very important thing which you may never forget when using the map. Use a
return statement, otherwise your array will end up with all items as undefined .

The lter operator


Let’s say that we want array of only the animals which are small. Using a for-loop we
would write something like this:

1 let small_animals = [];


2
3 for (let i = 0; i < animals.length; i ++) {
4 if (animals[i].size === "small") {
5 small_animals.push(animals[i])
6 }
7 }

for_loop_filter.js hosted with ❤ by G i t H u b view raw

Using the filter-operator we can write the same like this:


1 let small_animals = animals.filter((animal) => {
2 return animal.size === "small"
3 })

filter.js hosted with ❤ by G i t H u b view raw

The lter operator accepts the same parameters (current item, index and entire array) in
the callback function. But since we don’t use the index and the entire array, i’ve left them
out. The filter-operator also has the same other bene ts as the map . We also have to
use the return again to make the filter work properly. But this time we have to make
sure that the return returns a boolean value. If you don’t do this the lter will always
return false.

The reduce operator


Let’s say that we want to calculate the combined weight of all the animals in our array.
Using a for-loop we can write something like this:

1 let total_weight = 0;
2
3 for (let i = 0; i < animals.length; i++) {
4 total_weigth += animals[i].weight
5 }

for_loop_reduce.js hosted with ❤ by G i t H u b view raw

Using the reduce-operator we can write the same like this:

1 let total_weight = animals.reduce((weight, animal, index, animals) => {


2 return weight += animal.weight
3 }, 0)

reduce.js hosted with ❤ by G i t H u b view raw

The parameters in the callback function work a bit di erent than map and filter . It
works as follows:

• The rst parameter is the current value of the end value. We have to set the initial
value at the end of the function. In this case we set it to o . This could be any value
though.

• The second parameter is the current item in the array.

• The third is the index again.


• The last is the full array.

Again we have all the readability improvements of the map and filter . We also need to
use the return again. This time it’s important the we return the end value, the rst
parameter, at the end of each reduce function.

Conclusion
After these easy examples you should have a better understanding of how map , filter
and reduce work. These operators will shine even more when your code or data get’s
more complex. I would advice you to play with them if you don’t use them regularly
already. It can really make your code much easier.

. . .
Thanks for reading. Any feedback? Let me know. Also check my other articles:

• https://hackernoon.com/an-angular-2-webpack-setup-for-development-and-
production-3ea8bcc35e24

• https://hackernoon.com/global-http-request-error-catching-in-angular-
486a319f59ab

• https://medium.com/@luukgruijs/ngrx-e ects-setting-up-reusable-e ect-functions-


2b5fa299577b

• https://hackernoon.com/ngrx-store-reuse-reducer-logic-b6c0449e695d

Follow me on Medium and let’s connect on LinkedIn

Sign up for my newsletter


Get my new articles about Angular/Javascript straight into your inbox. No spam! Unsubscribe
anytime.

yourname@example.com Sign up
 formed on u p s c r i b e

Hacker Noon is how hackers start their afternoons. We’re a part of the @AMI family. We
are now accepting submissions and happy to discuss advertising & sponsorship
opportunities.

If you enjoyed this story, we recommend reading our latest tech stories and trending tech
stories. Until next time, don’t take the realities of the world for granted!

JavaScript Front End Development ES6 Map Javascript Filter Javascript

One clap, two clap, three clap, forty?


By clapping more or less, you can signal to us which stories really stand out.

1K 5

Luuk Gruijs Follow


Senior front-end developer writing about Angular and Javascript

Hacker Noon Follow


how hackers start their afternoons.

Das könnte Ihnen auch gefallen