Map, Reduce and Filter in JavaScript

Even if you don’t understand basic for loop iterations, you’re going to love this.

Map, Reduce and Filter are JavaScript methods used to iterate over an array. They just iterate over an array in order to make some computations.
There are two ways to iterate over an array and those are imperative and declarative. If you don’t know what are these then don’t worry. I am going to explain today in a much easier way possible.
When I started learning JavaScript a year ago I really didn’t know even a single programming language. Yes! I had to start from the start, being from a non-cs background it took me a lot of effort to understand simple for loop. once I became familiar with loops then I started learning higher-order functions as well and then I learned functions like map and filter.

As I already mentioned an iteration can be performed either imperative or declarative way. So enough talks…
let’s learn what is the difference between them then you’ll better understand the map, reduce, and filter!

So using the conventional method for using for loop iteration is known imperative method, whereas using these higher-order methods like the map is declarative!
still not clear? so let me put it this way… just pay attention to the word declarative, what does it mean?
Exactly, it has a proper declaration of what manipulations or mutations you want in your array
. let’s see it by example-

map an array of five natural numbers into the squares of those numbers!

function squareOfNumbers(array){
var arrayOfSquare = []
for(var i=0; i<array.length; i++){
return arrayOfSquare
squareOfNumbers([4,5,8,21,5]) => number * number)

that’s it! how clean and declarative it looks. anyone can even read it like a poem and understand what is going on here! it is simply mapping the existing array into the square of numbers, right?

let’s see them one by one with an example-

Creates a new array from an existing array with mutated (changed) values.
those values are the new result of the functions that apply to each element of the array. callback(currentValue, index, array)=>{
returns new values insted of currentValues
(i.e return currentvalue*2)

Parameters -
Callback- function that calls every element of the array, every time callback executes and returns the new value and adds to the new array.
currentValue(optional)- current value of the array!
index(optional)- index of the current element.
array(optional)- the array on which map is applied.

for instance-

let fullName = [‘Prakash’,‘Shivam’,‘Anu’].map(firstName => firstName + ‘ Agrawal’)
console.log(fullName); // ['Prakash Agrawal',Shivam Agrawal, Anu Agrawal]

As it has declarative nature so we know this function is used to filter out desired elements of the array.
for instance, there is an array of names and you want to filter out the names having lengths of more than 3.

Imperative way

let array = ['Amy','Prakash','Anubhav','Deepesh','Anu']
let newArray=[]
for(var i=0; i<array.length; i++){
console.log(newArray) //[ 'Prakash', 'Anubhav', 'Deepesh' ]

Declarative way (use of filter):

let newArray = ['Amy','Prakash','Anubhav','Deepesh','Anu'].filter(name=>name.length>3)
console.log(newArray) //[ 'Prakash', 'Anubhav', 'Deepesh' ]


Reduces the array to a single value! that’s all!
is it? that is all one need to know? No!
Reduce has big use in manipulations of the arrays in JavaScript!

Imperative Way:

//Add all the elements of the arrays and reducing it to one value.
function sumOfAll(array){
var sum = 0;
for(var i=0; i<array.length; i++){
sum = sum + array[i]
return sum
sumOfAll([1,2,3,4]) //10

Declarative way

var array = [1,2,3,4]
var sum = array.reduce((accumulator, currentValue)=>accumulator+currentValue,0)
console.log(sum) // 10

Why am I everytime showing you both ways because I want you to know the exact difference between them!
Understanding the Reduce-

now let’s understand what just happened?
reduce has two main parameters which are Accumulator and Current Value.

Accumulator has nothing when iterations starts or can say by default it is zero, or we can give some initial value as you can see I have given 0 after ‘accumulator+currentValue’ operation.
just like sum variable in imperative method, current values keep getting added into it and it’s value also keeps updating as updated accumulated value and after iteration of entire array it exits the iteration and returns the last accumulated value!
See this, you’ll understand it better if you didn’t-
intially by default:
accumulator = 0

so in this array- [1,2,3,4]
accumulator+currentValue = 0+1;
new accumulator value = 1
accumulator+currentValue = 1+2;
repeating this same again and again-
accumulator+currentValue = 3+3
accumulator+currentValue = 6+4
Iteration completed!
last accumulator value is 10.

I would suggest you all to take some array and practice each one of the above one by one, you will be comfortable soon with map, reduce, and filter

That’s it dear coders!


I write related to programming and web development

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store