The Fantastic Four: .map, .filter, .forEach, & .reduce array (iteration) methods
Tags: beginners, javascript, programming, array
Published: 2023-01-23 15:01:21


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6gofznl57is9459vuf62.png)An array (iteration) method is a function built into JavaScript that we use to apply to arrays. There are a few other great array methods but these particular four are always good to know and come in handy when needed. 

These methods take in four parameters: 

1.) A **callback function** to execute for each element in the array. Its return value is added as a single element in the new array. 

2.) The **element** being processed in the array. 

3.) **Index** of the current element being processed in the array. 

4.) The **array** the method was called upon. 

so it ends up looking something like: 
```
array.arrayMethod(element, index, array) {
// action
}
```
The array method **_.Map()_** creates a shallow copy of the original array populated with the results of calling a provided function on every element in the calling array. The result of the passed-in callback will be a new array with each element.

For example say I want a new array with every element multiplied by two: 

```
function double(numbers) {
    const doubled = numbers.map((number, i ,array) => {
        return number * 2;
    })
    return doubled;
}

double(numbers)
```
In the above example, I created a function that takes in an array of numbers 
``` 
const numbers = [1, 2, 3, 4, 5]; 
```
and using the map method it iterated over the array multiplying each number by two adding it to an array and returning in the place of the old one getting us this result:

```
//  [1, 2, 3, 4, 5] =>  [ 2, 4, 6, 8, 10 ]
```

_**side note:**_
**We can make this code so much cleaner! Because I'm not using the index or the array we can take those out of the parameter and just leave the element without the extra parentheses. We can also get rid of the variable that's holding the map function, the returns, and the curly braces so the whole inner function can just fit on one line of code like this:** 
```
return numbers.map(number =>  number * 2);
```
Next up we have the **_.filter()_** which just like **_.Map()_** returns an array of elements. It creates a shallow copy of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function.

for example, say I wanted an array of only the even numbers:

```
function onlyEvens(numbers) {
 const evens = numbers.filter((even, i, array) => {
    return even % 2 === 0;
 })
 return evens;
}
 
onlyEvens(numbers)
```
By using the filter method I was able to "filter" out any number that is % 2 === 0 thus giving me all the even numbers in a new array.

here's a cleaner look: 
```
return numbers.filter(even => even % 2 === 0)
```
And here's another example not involving math: 

```
function fiveAndBelow(words) {
    return words.filter(word => word.length <= 5 )
}

fiveAndBelow(["lala", "land", "I", "independent", "cakey", "developer"])

```


```
["lala", "land", "I", "independent", "cakey", "developer"] => [ 'lala', 'land', 'I', 'cakey' ]
```

Next we have the **_.forEach()_** method which executes a provided function once for each array element callbackFn will not visit any elements added beyond the array's initial length when the call to **_.forEach()_** began._ (it's basically a for loop but less work)_

for example, say you want to print out each element in an array:

```
function print(words) {
    return words.forEach(word => console.log(word))
}

print(["lala", "land", "I", "independent", "cakey", "developer"])

*prints*
lala
land
I
independent
cakey
developer
```
The **_.forEach()_** method iterated over the array and returned a console log of each element.


Another example, say you want the total sum of an array of numbers: 
```
function findSum(numbers) {
    let sum = 0
    numbers.forEach(number => sum += number)
    return sum;
}
```

The method iterated over the array adding each element to the sum value giving us the overall sum of the array once returned.

But of course for anything math-related like finding the total sum of an array you can also use **_.reduce()_** method.

Speaking of **_.reduce()_** method it executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.

unlike the other three reduce needs two more parameters the accumulator and initial value. The **accumulator** which is the value resulting from the previous call to callbackFn. On first call, **initial value** if specified, otherwise the value of array[0].

(_**So if you think back to the forEach method the initial value is basically the let sum = 0, and if you don't set one it will just latch on to the first index in the array and use that.**_)

for example, say you want the total product of an array of numbers: 

```
function findProduct(numbers) {
    return numbers.reduce((accum, num) => accum *= num, 1)
}
```
The accumulator is holding on to that initial value iterating over the array and multiplying the elements together. 

_**side note:
You can also one-line this whole function creating less and cleaner code by using a function expression instead of a function declaration:**_

```
const findProduct = numbers => numbers.reduce((accum, num) => accum *= num, 1)
```

In conclusion, although they might not be everyone's top choice the map, filter, forEach, and reduce methods are great tools to know and will always come in handy when needed. 


**Resources**:
_Array Methods_: 
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

https://www.geeksforgeeks.org/javascript-array-iteration-methods/

https://youtu.be/Urwzk6ILvPQ

_Arrow functions_:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

https://youtu.be/h33Srr5J9nY

_Function Expression_:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/function

https://youtu.be/37ly8tCGFWA