DEV Community

Tatiana Bowman
Tatiana Bowman

Posted on • Updated on

The Fantastic Four: .map, .filter, .forEach, & .reduce array (iteration) methods

Image descriptionAn 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
}
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

In the above example, I created a function that takes in an array of numbers

const numbers = [1, 2, 3, 4, 5]; 
Enter fullscreen mode Exit fullscreen mode

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 ]
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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"])

Enter fullscreen mode Exit fullscreen mode
["lala", "land", "I", "independent", "cakey", "developer"] => [ 'lala', 'land', 'I', 'cakey' ]
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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)
}
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)