Reacting to Built-in Iterator Methods
Tags: react, javascript, webdev, programming
Published: 2022-08-25 21:32:00

When working with arrays in Javascript and React, there are times when you need to iterate through them. You can write a loop to do that and that’s perfectly fine. However, there are iterator methods already built into the array object that can accomplish the same result. Using these built-in iterators make your code more readable and cleaner. We will be going over some of the most used ones and give a sample code for each.

The array iterators forEach, map, filter, some, find and findIndex all take a callback function as their parameter and the callback function takes three parameters. The first parameter is the item value, the second is the index of the item, and the third is the array itself.

In my time in the second phase of Flatiron School I have found these methods to be very useful when working with backend API databases. In order to render this information onto our page and manipulate it on the DOM we need to use these different methods quite a bit. We will be going over some of the iterator methods that will enhance your ability to manipulate data in React. With that being said, let's dive into some code.

We’re going to be using an array of names called “names” for some of the sample code for brevity.

let names = ["Barrett",
    "Jacob",
    "Matthew",
    "Gilbert",
    "Simon",
    "Nick",
    "Erick",
    "John"
];


## **The .forEach() method**

This iterator executes a callback function for each item in the array. It doesn’t return any value. Use it when you want to perform a task without expecting any return value. For instance, if you have an array of names and want to print a greeting message for each name, you can use the forEach method. The code would look like this.
```
names.forEach((value) => {
    console.log("Hello " + value);
});
-------OUTPUT-------
Hello Barrett
Hello Jacob
Hello Matthew
Hello Gilbert
Hello Simon
Hello Nick
Hello Erick
Hello John
```

## **The .map() method**
This array iterator returns a new array as a result of executing a callback function for each array element. This method skips elements with no value and does not modify the original array.

This method is especially useful in React when we want to iterate over an array and pass down each individual value to a component that will make a new item to contain all of our information that we wish to render onto our application. Below is an example of how this would be utilized within our React application.

```
//mapping names
let mappedArray = names.map((value) => ({
      <NamesCard value={value}/> 
})
```

For each value within our names array, we have created a new component in which we have passed down each value as props(which is a way to pass down data from different components) into that new component where we can make a new item for each value we have inside of our name array and render that information onto our application.


## **The .filter() method**

This array iterator also returns a new array of elements that passes the conditional check. For instance, if we want to find all the names that contain “ae”, we can use the filter method. The new array should have two elements, Barrett and Matthew. The code would look like this.

```
//filtering names
let aeMatchingElements = names.filter((value) => {
    return value.includes("ae");
});
//printing names
aeMatchingElements.forEach((value) => {
    console.log(value);
});
-------OUTPUT-------
Barrett
Matthew
```


## **The .some() method**

This array iterator checks if some of the elements of an array meet a condition. It returns false if none of the elements pass the test and true if at least one passes the test. Now the scenario is we want to check if some of the people living in that community are adults. We can use the “some” method. Your code would look something like this.

```
let ages = [16, 17, 20, 24, 29];
let someAdults = ages.some((value) => {
    return value >= 18;
});
console.log(someAdults);
-------OUTPUT-------
true
```


## **The .find() method**

This array iterator returns the first element that meets the condition. Otherwise, undefined is returned. For instance, using the “ages” array we’ve used for the “some” method, we can find the first non-adult by using the find method. The code would look like this.

```
let ages = [16, 17, 20, 24, 29];
let nonAdult = ages.find((value) => {
    return value < 18;
});
console.log(nonAdult);
-------OUTPUT-------
16
17
```

## **The .findIndex() method**

This array iterator returns the index of the first element that meets the condition. Otherwise, -1 is returned to indicate no element is found. For instance, using the “ages” array, we can find the position of the first occurrence of the value 17. The code would look like this.

```
let ages = [16, 17, 20, 24, 29];
let firstOccurrence = ages.findIndex((value) => {
    return value == 17;
});
console.log(firstOccurrence);
-------OUTPUT-------
1
```

indexOf functions take two parameters. The first parameter is the value for which index we’re looking for and the second is the search starting position. The second parameter can be omitted if you want to start from the first position of the array.


## **The .indexOf() method**

This array iterator does the same thing as the findIndex method. The only difference is that it doesn’t take a callback function as a parameter. It takes two parameters. For instance, using the “ages” array, if you want to start looking for the value 17 starting from the third position, you would use the indexOf. The code would look like this.

```
let ages = [16, 17, 20, 24, 29];
occurrence = ages.indexOf(17, 3);
console.log(occurrence);
-------OUTPUT-------
-1
```

The value -1 is returned because we specified the search starting position. Staring from the third position it reads from left to right which from the third position we can see there is no value of 89 read. Therefor the output is going to be -1. If we started from position zero, then the value 1 would have been returned.


## **The .reduce() method**

This array iterator is used to reduce all the elements of the array to a single value by executing the callback function. The callback function takes four parameters. The first is the total, which means the value returned by the callback after each execution. The second is the element value, the third is the index of the element and the fourth is the array itself.

For instance, using the “ages” array, if you want to sum up all the elements, you can use the reduce method. The code would look like this.

```
let ages = [16, 17, 20, 24, 29];
let sum = ages.reduce((sum, value) => {
    return sum += value;
});
console.log(sum);
-------OUTPUT-------
106
```

## **Conclusion**

These are just a few of the many iterator methods that will help you become a better developer while also writing much cleaner and readable code. These built in methods are especially useful in React where you will be creating a new array without destructively modifying the original array for each event listener you add to your application for the user to interact with. Now go try them out yourself and become a better coder!