find(), filter(), and map() Explained As Party Games
Tags: javascript, tutorial
Published: 2023-11-07 16:59:16

Hello fellow coders! When beginning my journey of learning array iteration methods (including find(), filter(), and map()), I struggled to keep track of which method did what, and how to use each method. Can you relate? Well, today we’re going to turn these methods into analogies that you can remember! First I’ll tell you a story and then we’ll relate it to the method. I’ll include some simple code examples, so open Replit or a coding project and follow along!

#What are methods and why are they important?
The word “method” was hard for me to understand at first, but we can think of “methods” as “actions” or “steps”.
The methods we’re talking about today can seem hard to grasp at first, so let’s orient ourselves with *why* we want to learn them. 
As software engineers, we want to write code efficiently and these methods help us reach that goal. Each of these methods is important because they provide us with cleaner code that is easier to read. Also, we often can write fewer lines of code when we use these methods.

Before we get started with the examples below, it's important to remember that none of these methods are Destructive (they WON'T mutate the original array). Please keep that in mind as you read through the stories below because the stories aren't perfect metaphors.

Now let's learn these methods!

#find() Method
SURPRISE! It’s your birthday and your best friend organized a surprise party! You’ve spent the last couple of hours eating cake, opening presents, and socializing, but now it’s time to play party games! There are some fun party games planned and the first one is a scavenger hunt!

This is going to be a quick game because everyone only has 1 item to find: a red balloon. You are going to have to move quickly and grab the FIRST red balloon you see (or someone else will find a red balloon first!). The referee says “Go!”, and everyone scurries away. In your mind, you are ONLY looking for red balloons and huzzah! You see one! You grab it and run back to the referee. You WON! As everyone congratulates you, you look around and realize that the room is full of red balloons, but you only SAW the first red balloon you come across. All of a sudden, you realize that you have just used the find() method without realizing it:
We can imagine that all the balloons in the area where you looked could be translated into an array like this:

```
const balloonArray = [
  {color: 'blue', condition: 'inflated', inTrash: 'no', number: 1},
  {color: 'red', condition: 'inflated', inTrash: 'no', number: 2},
  {color: 'yellow', condition: 'inflated', inTrash: 'no', number: 3},
  {color: 'green', condition: 'inflated', inTrash: 'no', number: 4},
  {color: 'red', condition: 'inflated', inTrash: 'no', number: 5},
  {color: 'blue', condition: 'inflated', inTrash: 'no', number: 6},
  {color: 'yellow', condition: 'inflated', inTrash: 'no', number: 7},
  {color: 'blue', condition: 'inflated', inTrash: 'no', number: 8},
  {color: 'red', condition: 'inflated', inTrash: 'no', number: 9},
  {color: 'green', condition: 'inflated', inTrash: 'no', number: 10}
];

```
And you were acting like the find() method, looking for the FIRST red balloon you came across:

```
let findRedBalloon = balloonArray.find(balloonObject => {
  if(balloonObject.color === "red"){
    return balloonObject;
  };
});

console.log(findRedBalloon);

```
Let's look at what our console.log() returned in our browser's console:

![findRedBalloon console.log() result](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/db3nq2zdbzpzyq7uvzoy.png)

It is easy to see from our console.log() that the find() method used in findRedBalloon is ONLY returning the 1st red balloon in our array. findRedBalloon returned the red balloon with the key-value pair of "number: 2". We can verify that this is indeed the first red balloon in the array by looking at our balloonArray.

###Let's break down the find() method more in-depth by coding together
First, we'll declare a variable, then call the find() method on the balloonArray (the array holding all the balloons):
```
let findRedBalloon = balloonArray.find();

```

Inside our find() method we need a callback function, and we'll write one here as an arrow function so it is even cleaner and easier to read. While we're at it, we'll also include a parameter named "balloonObject" so it reminds us that we are going to be looking through the balloonArray at each individual balloon object inside it:

```
let findRedBalloon = balloonArray.find(balloonObject => {
//our next code goes here
});

```

Our code is looking great, but now we need to define what we are doing with the balloonObject. Since we are using find() to find the 1st red balloon we come across, let's use an “if” statement to find a red balloon and return the entire balloonObject. In order to do this, we'll use dot notation to access the "color" value stored inside our balloonObject:

```
let findRedBalloon = balloonArray.find(balloonObject => {
  if(balloonObject.color === "red"){
    return balloonObject;
  };
});

```

And now you understand the find() method! It's easy to imagine that instead of just returning the balloonObject like we did above, you could run the object through a function, or "do" something more complicated with it at this point.

#filter() Method
Back at your birthday party, people have barely stopped congratulating you on your win when the referee announces the next game. Each competitor starts with a dumpster full of balloons. The competitor will pull a balloon out of the dumpster. If the balloon is red, they will run across the room and place it in a basket. If it isn't red, the competitor will throw it on the floor out of the way. 

As soon as the referee says "Go!", you start quickly working through the dumpster, evaluating one balloon at a time. If it's red, you get it to the basket as quickly as possible. If it's not red, you throw it out of your way. Since you're so focused, you get done before anyone else! As you wait by your basket of red balloons while your friends finish sorting through their balloons, you suddenly realize that you have just acted like the filter() method, looking for all the red balloons you came across in your dumpster (array):

```
let filterRedBalloons = balloonArray.filter(balloonObject => {
  if(balloonObject.color === "red"){
    return balloonObject;
  };
});

console.log(filterRedBalloons);

```
Let's look at what our console.log() returned in our browser's console:

![filterRedBalloons console.log() result](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v2bemlfx1cnb3wjcfi2a.png)

If we check our balloonArray, we can verify that filterRedBalloons did indeed return all the red balloons in the array.

###Let's break down the filter() method more in-depth by coding together
To make this example easier to understand, we’ll assume that the balloons in your dumpster were the same as the balloonArray we used in the previous example. 

The process you went through to sort balloons would be the find() method: go through the ENTIRE array and find ALL the red balloons. Don't stop until you have sorted all the balloons.

In code, we would first declare a variable, then call the filter() method on the balloonArray like so:
```
let filterRedBalloons = balloonArray.filter();

```

Inside our filter() method we need a callback function, and we'll once again write ours as an arrow function. While we're at it, we'll make a parameter named "balloonObject":

```
let filterRedBalloons = balloonArray.filter(balloonObject => {
//our next code goes here
});

```

Just like we did in the find() example, we're now going to write code to do something with the balloonObject. In our example we want to collect all the red balloons, so we'll use an “if” statement and dot notation to access the color value stored inside our balloonObject and compare it to "red":

```
let filterRedBalloons = balloonArray.filter(balloonObject => {
  if(balloonObject.color === "red"){
    return balloonObject;
  };
});

```

At this point, instead of just returning balloonObject, we could do something with the balloonObject. But for this example, let's end here and move on to learn about map()!

#map() Method
It’s time for the final game of the party, and in hindsight, you realize the party planners were using this game to clean up the party...
The game goes like this: Everyone has to pick up 10 balloons off the floor (it doesn't matter what color, so long as you pick up 10). To win the game, you will need to pop all the balloons as quickly as possible. Then you'll need to pick up all the popped pieces and throw them into the trashcan. Whoever pops 10 balloons first wins and gets to take home all the leftover cupcakes as their prize!

You get two teammates for this challenge, and after a quick huddle, your team decides that you will be in charge of grabbing balloons off the floor. Once you have one you'll hand it to your 1st teammate. They'll be in charge of popping the balloon, and your 2nd teammate will pick up the balloon pieces and throw them in the trash.

The referee says "Go!" and you begin to pick balloons off the floor and hand them to your 1st teammate one at a time. When you hand the balloon to your 1st teammate, she pops it and your 2nd teammate quickly picks up the pieces and runs over to the trashcan to throw them away. You’ve found an efficient system that’s better than your teammates, and before you know it you’ve popped 10 balloons! Your team won! Everyone congratulates you for being undefeated at party games, and while you munch on another cupcake, you start to realize that you and your teammates just did the map() method. You had 10 balloons (your array), that you sorted through individually (your balloonObject). You handed each balloonObject off to your 1st teammate, who, in code, would be a function. That function ran, and then the 2nd teammate (also a function) was passed the balloonObject. Your code would look something like this:

```
let mapBalloons = balloonArray.map(balloonObject => {
  popBalloon(balloonObject);
});

function popBalloon(balloonObject){
  balloonObject.condition = "popped";
  throwBalloonAway(balloonObject);
};

function throwBalloonAway(balloonObject){
  balloonObject.inTrash = "yes";
  console.log(balloonObject);
};

```
Let's look at what our console.log() returned in our browser's console:

![balloonObjects after console.logging](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/el4s6o6d96gc9fw3v58t.png)

Our console.log() shows us that our "condition" and "inTrash" values have changed in each object (remember, this is a non-destructive method, so the original array has NOT changed). 

###Let's break down the map() method more in-depth by coding together

First, we'll declare a variable, then call the map() method on the balloonArray:

```
let mapBalloons = balloonArray.map();

```

Our map() method needs a callback function, so let's provide one in the form of an arrow function, and add a parameter of "balloonObject":

```
let mapBalloons = balloonArray.map(balloonObject => {
//our next code goes here
});

```

Next we're going to call a function that map() will pass each ballonObject individually into:

```
let mapBalloons = balloonArray.map(balloonObject => {
  popBalloon(balloonObject);
});

```

And we'll assume we've already written these functions which each change a value inside the object. The important thing to realize here is that map() is passing each individual balloonObject into these functions. We didn't have to write out a for loop or anything!

```
function popBalloon(balloonObject){
  balloonObject.condition = "popped";
  throwBalloonAway(balloonObject);
};

function throwBalloonAway(balloonObject){
  balloonObject.inTrash = "yes";
};

```
(These functions are pretty simple, but you can imagine that you could do some pretty complex things with your own functions).

#Let's review
Find(), filter(), and map() can be daunting when you are first introduced to them, but I hope these "party game" examples have shown you that at their core they aren't very complicated and can be very helpful.

So, the next time you use one of these methods, think back to the party games we talked about here and reference the notes below if you need to!

####find()

- Find the first red balloon

####filter()

- Collect all the red balloons

#####map()

- Pop all the balloons



**Thanks for reading!**