# How to Use Map, Filter and Reduce in JavaScript

Functional programming is making a quick splash in the field of development these days. And for these reasons: functional programming can let you write more declarative code which is easier to understand, refactor and test.

one of the most important cornerstones of functional programming is the user list and its operations.

so, this article will give you a close look at what we can call the "Big Three" operations of list Map, Filter and Reduce.

# How to use Map

sometimes we found ourselves in a situation where we have to take an array and modify every element in it in exactly the same way. For example- do a cube of every element in the array, and find out the usernames from the list of users.

**map** is a method to do that exactly. It is defined on **Array. prototype** so you can call it on any Array and it accepts a callback as its first argument.

the syntax is shown below

```javascript
array.map(function(currentValue, index, arr), thisValue)
```

when you call map on an array, it executes the callback on every element within it, returning a new array containing all the values returned by the callback.

under the hood, **map** passes three arguments to your callback

1. the *current item* in the array
    
2. the *array index* of the current item
    
3. the entire array you called **map** on
    

## map in practice

we have an array of object family , our task is to return an array that contains the family members name.

```javascript
const family = [
   { name: 'prakash', city: 'mumbai' },
   { name: 'vimal', city: 'pune' },
  { name: 'maruf', city: 'chennai' },
  { name: 'anil', city: 'mumbai' },
   { name: 'amit', city: 'mumbai' }
 ]
// using map
const members = family.map( function (member, index, array) {
  return member.name ;
})
console.log( members);
O/p- [ 'prakash', 'vimal', 'maruf', 'anil', 'amit' ]
```

here I included the index and array, to let you remind them they are there if you want to use them you can use them.

one more succinct way of writing the above code is using the arrow function

```javascript
const members = family.map( members => members.name)
console.log(members);
o/p- [ 'prakash', 'vimal', 'maruf', 'anil', 'amit' ]
```

the advantage of using map over loops is that we don't have to manage the state of the loop manually making our code simpler and more maintainable. One more advantage is that we can directly operate on every element of the array instead of having to index into the array making it more readable.

but this all can be done by **forEach** loop so why do we use a **map** over it, the reasons are-

1. **forEach** returns **undefined** so it can not be chained with another array method, while on the other side, **map** returns an array, so it can perform chaining.
    
2. **map** returns a finished product, rather than requiring us to mutate the array inside the loop.
    

**point to remember while using a map-**

<mark>the callback you pass to the </mark> **<mark>map</mark>** <mark> must have an explicit </mark> **<mark>return</mark>** <mark> statement, or the map will split out an array of </mark> **<mark>undefined</mark>**<mark>.</mark>

# Use of Filter

our next array operation is **filter,** it does the same as its name reveals it takes our array and filters out the unwanted elements.

the syntax for filter is :

```javascript
array.filter(function(currentValue, index, arr), thisValue)
```

**filter** also passes three arguments to your callback

1. the *current item*
    
2. the *current index*
    
3. the *array* you called **filter** on
    

## Filter in practice

we have an array of words we have to return only those strings whose length is less than 8.

```javascript
const words = ['Python', 'Javascript', 'Go', 'Java', 'PHP', 'Ruby'];
const result = words.filter(word => word.length < 8);
console.log(result);
o/p- [ 'Python', 'Go', 'Java', 'PHP', 'Ruby' ]

```

**filter** also few stuffs as the map does

* avoid mutating the array inside the **for** or **forEach** loop.
    
* assign its result directly to a new variable, rather than push into an array we defined elsewhere.
    

**point to remember while using filter -**

<mark>just like </mark> **<mark>map</mark>**<mark>, in </mark> **<mark>filter</mark>** <mark> you also have to include the return statement and you make sure it returns a boolean value.</mark>

<mark>if in case you forget your return statement your </mark> **<mark>filter</mark>** <mark> will return undefined which </mark> **<mark>filter</mark>** <mark> will </mark> **<mark>coerce</mark>** <mark> to </mark> **<mark>false</mark>**<mark>. and this will not throw an error but it silently return an empty array!</mark>

## Use of map and filter together

we have been provided with an array named family we have to return an array which contains only those members whose city is mumbai

```javascript
const family = [
   { name: 'prakash', city: 'mumbai' },
   { name: 'vimal', city: 'pune' },
  { name: 'maruf', city: 'chennai' },
  { name: 'anil', city: 'mumbai' },
   { name: 'amit', city: 'mumbai' }
 ]
const arrOfName = family.filter(member => member.city=="mumbai");
const members = arrOfName.map(member => member.name)
console.log(members)
o/p- [ 'prakash', 'anil', 'amit' ]
```

## Use of Reduce

**map** creates a new array by transforming every element in an array individually. **filter** creates a new array by removing those elements that don't belong. **reduce** on the other hand takes all the element of the array and reduce them into a single value.

syntax for reduce

```javascript
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
```

reduce passes four value to your callback

1. the *current value*
    
2. the *previous value*
    
3. the *index*
    
4. the *array you called reduce on*
    

Notice that the callback gets a *previous value* on each iteration. On the first iteration, there *is* no previous value. This is why you have the option to pass **reduce** an initial value: It acts as the "previous value" for the first iteration, when there otherwise wouldn't be one.

you should keep in mind that reduce returns a single value not an array

## Reduce in practice

```javascript
const arr = [1, 2, 3, 4, 5]
const sum = arr.reduce( (accumulator, current ) => accumulator+current ,0)
console.log(sum);
o/p - 15
```

in the above example if you observe we have passed 0 as the initial value to the accumulator and after complete execution of the reduce it returns a single value.

<mark>what if in the above example if we don't pass the initial value then your initial value of accumulator will be the element at the first index of your array and your current will start from the element at the second index of your array.</mark>

### points to remember while using reduce

* don't forget return
    
* don't forget an initial value
