Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
September 15, 2022 06:17 pm GMT

Map(),Filter(),reduce() with important interview questions

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:

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.

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

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]

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.

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.

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

arr.reduce(callback[, initialValue])

Lets take example for finding sum of all array elements

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.

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 fullnameconst 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.

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.

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 methodconst 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.

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

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

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},  ];//Chainingconst 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

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

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.


Original Link: https://dev.to/srishtikprasad/mapfilterreduce-with-important-interview-questions-1ae5

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To