Map, Filter & Reduce in JavaScript

Map

This function returns a new array with a callback function acting upon every element within the array. Map will run a callback function that takes 3 arguments. The first being the “current item” in the array (this is a required argument), the second being the “index” within the array of the current item (this is an optional argument), finally, the last argument in the callback is the entire array itself (this is also an optional argument).

Here is an example of an array of objects I have created which contains a few of my favourite movies (Don’t judge me!), each with their movie name and the name of the actresses/actors who starred in them.

var favouriteMovies = [
{'name':'aliens','mainStar':'Sigourney Weaver'},
{'name':'Predator','mainStar':'Arnold Schwarzenneger'},
{'name':'Godzilla','mainStar':'Bryan Cranston'},
{'name':'Blade','mainStar':'Wesley Snipes'},
{'name':'Prometheus','mainStar':'Noomi Rapace'}
]

For this example I will just be extracting the movie name from the object of arrays using map and to do this is seen below.

var movieName = favouriteMovies.map(function(currItem){return currItem.name});

As you can see I have created a variable called “movieName” and set it to equal to “map” over the “favouriteMovies” array with one parameter defined (the mandatory parameter which represents the current item in the array) and I am returning the key “name” from the “favouriteMovies” array, copy and paste both the map function and object of arrays into a code editor such as https://playcode.io and look at the result, or create your own :).

Below is the result from the console.

However you can write your own function and insert it into the parameter of the map function as seen below.

This will produce the exact same output as above however it is just some nice “syntatic sugar”.

Filter

Filter does exactly what it says on the tin, it will take in an array and filter out elements of the array depending on the criteria you set, i.e. numbers over 20, strings not equal to “david” etc. Filter works the same way as map in that it takes a callback as its first argument and that callback has 3 arguments (first is current item, second is current index, third is the whole array), filter will run the callback on every element within the array and return a new array that contains only elements which have returned true for the callback criteria, an example is below.

var icecreams = [
{'flavour':'chocolate','rating':'5'},
{'flavour':'vanilla','rating':'9'},
{'flavour':'strawberry','rating':'8'},
{'flavour':'salted caramel','rating':'9'}
]
var filterIcecreams = icecreams.filter(function(currItem){
return currItem.rating >8
})

As you can see from the above, we have created an array of objects pertaining to an ice cream flavour as well as its rating, I have then performed a filter operation on the array to only return ice creams that have a rating greater than 8. The output can be seen below which will be the flavours “vanilla” and “salted caramel”

NOTE: One thing to remember when using map, reduce and filter is that within the callback function it must use the “return” keyword, otherwise your variable will return “undefined”.

Reduce

Reduce as its name suggests reduces, however, to put it more professionally, the reduce function takes in all of the array elements and “reduces” them into a single value, furthermore, reduce differs from map and filter in that it supports 4 arguments within its callback (first being the current value, second being the previous value, third being the current index and finally the fourth is the array you are looping over). Reduce gives you the option to set the initial previous value (Which you can do by writing a comma and then the value after the closing “}”)as on the first loop iteration there isn’t a previous value present and is the reason as to why you can pass an initial value to reduce. The most basic usage of reduce is to sum a list of numbers.

var myNumbers = [9,8,7,6,5,4,3,2,1];
var sumOfMyNumbers = myNumbers.reduce(function(previous,current,myIndex,myArray){
console.log(previous)
console.log(current)
return previous+current
},0);
console.log(sumOfMyNumbers)

As you can see from the example above I have an array of numbers and return the sum of the previous value adding to the current value, in addition, I have also set an initial value of 0, so the reduce will begin from 0. The first value of “previous” is 0, and the first value of “current” is 9, however, if I change the initial value to be 5 and not 0, then the first “previous” value is 5 and the total then becomes 50, not 45 because I have told the reduce to begin from 5 and not 0. You could also reduce to find the average of a group of numbers too

All in all, these 3 methods are a great way to implement list operations within JavaScript, however, this tutorial is a basic example of this and implements them using ES5 not ES6, with ES6 you can use more shorthand features such as arrow functions.

Hope you enjoyed this article, I will continue to learn and share my knowledge, any feedback is thoroughly appreciated 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: