Map(),Filter(),reduce() with important interview questions
Tags: javascript, beginners, webdev, array
Published: 2022-09-15 18:17:27

Map, reduce, and filter are all array methods in JavaScript. Each one will iterate over an array and perform a transformation or computation. Each will return a new array based on the result of the function.
In this article you will learn about why and how to use map, filter, reduce.
#Map
The map() method is used for creating a new array from an existing one, applying a function to each one of the elements of the first array.
##syntax:

```javascript
var new_array = arr.map(function callback(element, index, array) {
    // Return value for new_array
}[, thisArg])
```
So, the original arr.map function takes a callback function as an argument and that callback function can have three arguments passed into it :
a. current value
b. index of the current value [optional]
c. array [optional]
##Implementation of Map()
Callback function will iterate for all the values of array arr and modify the array and store the value in the new array.
Using map function we need not to initialize new array.

Lets say we have an array and we want another array having all the values double the previous one.

```javascript
const arr=[1,2,3,4,5];

function double(x)
{
  return x*2;  
}
const output=arr.map(double);
console.log(arr);

```
writing the same code using arrow function

```javascript
const output=arr.map((x)=>{
  return x*2;  
});
console.log(arr);

```
#Filter
The `filter()` method takes each element in an array and it applies a conditional statement against it. If this conditional returns true, the element gets pushed to the output array. If the condition returns false, the element does not get pushed to the output array.
So, the original Array.filter function takes a callback function as an argument and that callback function can have three arguments passed into it :
a. current value
b. index of the current value [optional]
c. array [optional]



```javascript
var new_array = arr.filter(function callback(element, index, array) {
    // Return true or false
}[, thisArg])
```
Lets say we want to filter out odd numbers from array.

```javascript
const arr=[1,2,3,4,5]

function isOdd(x)
{
   return x%2; 
}
const output=arr.filter(isOdd);

console.log(output);

```
 Another example we can take is, to find numbers in array greater than 4.

```javascript
const arr=[1,2,3,4,5]
const output=arr.filter((x)=>{ 
return x>4
});
console.log(output);

```
#Reduce
The callback argument is a function that will be called once for every item in the array. This function takes four arguments, but often only the first two are used.

accumulator - the returned value of the previous iteration
currentValue - the current item in the array
index - the index of the current item [optional]
array - the original array on which reduce was called [optional]

The initialValue argument is optional. If provided, it will be used as the initial accumulator value in the first call to the callback function.
##Syntax

```javascript
arr.reduce(callback[, initialValue])
```
Lets take example for finding sum of all array elements

```javascript
const arr=[1,2,3,4,5];

const output=arr.reduce(function(accumulator,currentIdx){
    acc+=curr;
    return acc;
});
console.log(output);

```
Lets clear our concepts by trying some important question on these array methods.

Q1. Given an array of objects users, print fullname. 

```javascript
const users=[
  {firstName:"john",lastName:"Biden",age:26},
  {firstName:"jimmy",lastName:"cob",age:75},
  {firstName:"sam",lastName:"lewis",age:50},
  {firstName:"Ronald",lastName:"Mathew",age:26},  
];
//List of fullname
const output=users.map((x)=>{
    return x.firstName+" "+x.lastName;
})
console.log(output);
```

Q2. Given an array of objects users, print user of particular age along with their frequency.

```javascript
const users=[
  {firstName:"john",lastName:"Biden",age:26},
  {firstName:"jimmy",lastName:"cob",age:75},
  {firstName:"sam",lastName:"lewis",age:50},
  {firstName:"Ronald",lastName:"Mathew",age:26},  
];
```

Before proceeding forward think 🤔 which array method we can use here!
Analogy->Since we want to reduce our list to one object denoting all ages and find different value with count of each value hence we can use 'reduce' here.

```javascript
const users=[
  {firstName:"john",lastName:"Biden",age:26},
  {firstName:"jimmy",lastName:"cob",age:75},
  {firstName:"sam",lastName:"lewis",age:50},
  {firstName:"Ronald",lastName:"Mathew",age:26},  
];
//using reduce array method
const output=users.reduce(function(acc,curr){
    if(acc[curr.age])
    //if present in array object
    {
        acc[curr.age]++;            
    }else{
    //if not present in array object
      acc[curr.age]=1;      
    }
    return acc;
},{})
console.log(output);
```
Q3.Print object having marks greater than 60 and rollNumber greater than 15.

```javascript
let student =[
 {name:"Smith",rollNumber:31,marks:80},
 {name:"Jenny",rollNumber:15,marks:69},
 {name:"John",rollNumber:16,marks:35},
 {name:"Tiger",rollNumber:7,marks:55}
];
const details= student.filter((x)=>x.marks>60 && x.rollNumber>15);
console.log(details); 
 
```
Q4.Print sum of marks of all the student 

```javascript
let student =[
 {name:"Smith",rollNumber:31,marks:80},
 {name:"Jenny",rollNumber:15,marks:69},
 {name:"John",rollNumber:16,marks:35},
 {name:"Tiger",rollNumber:7,marks:55}
];
const details = student.reduce((acc,curr)=>{
    return acc+=curr.marks;
},0);
console.log(details);
``` 
###Chaining of array methods is one of the speciality of map(),filter(),reduce().

Q5.List of all firstName from array whose age is more than 30

```javascript
const users=[
  {firstName:"john",lastName:"Biden",age:26},
  {firstName:"jimmy",lastName:"Cob",age:75},
  {firstName:"Sam",lastName:"Lewis",age:50},
  {firstName:"Ronald",lastName:"Mathew",age:26},  
];
//Chaining
const output=users.filter((x)=>x.age>30).map((x)=>x.firstName);
console.log(output);
```
Q6.Print the names of students who scored more than 60

```javascript
let student =[
 {name:"Smith",rollNumber:31,marks:80},
 {name:"Jenny",rollNumber:15,marks:69},
 {name:"John",rollNumber:16,marks:35},
 {name:"Tiger",rollNumber:7,marks:55}
];
const ans=student.filter((x)=> {
return x.marks>60}).map((x)=>{return x.name});
console.log(ans);
 
```
Q7.Print total marks for students with marks greater than 60 after 20 marks have been added to those who scored less than 60

```javascript
let student =[
 {name:"Smith",rollNumber:31,marks:80},
 {name:"Jenny",rollNumber:15,marks:69},
 {name:"John",rollNumber:16,marks:35},
 {name:"Tiger",rollNumber:7,marks:55}
];

const totalMarks=student.map((stu)=>{
    if(stu.marks<60){
        stu.marks+=20;
    }
    return stu;
}).filter((stu)=>stu.marks>60).reduce((acc,curr)=>acc+curr.marks,0);
console.log(totalMarks);
```
I hope that this blog might be helpful to you. I have done my best to explain each array method with suitable examples covering some crucial questions to answer to ace your interview and gain a deeper understanding.
Please leave any questions in the comment box, and I'll do my best to respond.
If you find this helpful do like ❤️ it and follow me for more such blogs.