Javascript Interview Questions ( map, filter and reduce ) - Polyfills and Output Based Questions
Summary
TLDRThis video script offers an in-depth exploration of JavaScript's array methods: map, filter, and reduce. It begins by explaining the purpose and functionality of each method, demonstrating their use through practical examples. The script then delves into creating polyfills for these methods from scratch, showcasing a deep understanding of JavaScript's prototypical inheritance. To solidify concepts, the script addresses common interview questions, providing solutions using map, filter, and reduce in various scenarios. The tutorial aims to prepare viewers for technical interviews, emphasizing the importance of these methods in JavaScript development.
Takeaways
- 📚 The video discusses the use of JavaScript array methods: map, filter, and reduce, which are fundamental for transforming and computing data within arrays.
- 🔍 Interviewers often ask about these methods in JavaScript interviews, including their functionality, differences, and how to implement them from scratch.
- 🛠 The 'map' method is used to create a new array by applying a function to each element of an existing array, potentially returning a transformed array.
- 🔎 The 'filter' method evaluates each element in the array against a condition; elements that meet the condition are included in the output array.
- 🔄 The 'reduce' method condenses an array into a single value by applying a function to each element that accumulates a result.
- 💡 The script provides examples of using these methods with JavaScript code, demonstrating how to multiply array elements, filter based on conditions, and calculate sums.
- 👩🏫 The presenter also covers how to create polyfills for these methods, showing custom implementations of 'myMap', 'myFilter', and 'myReduce'.
- 🔑 Differences between 'map' and 'forEach' are highlighted, emphasizing that 'map' returns a new array while 'forEach' does not return anything and can mutate the original array.
- 🔗 The ability to chain methods after 'map' and 'filter' due to their return value is contrasted with 'forEach', which cannot be chained because it does not produce an array.
- 📝 The script includes practical interview questions and demonstrates how to solve them using the discussed array methods, such as extracting student names in capital letters or filtering students based on marks.
- 📈 Advanced use cases are also covered, such as combining 'map' and 'filter' to solve more complex problems, like adding grace marks to students and then calculating the sum of their scores.
Q & A
What are the primary purposes of the 'map', 'filter', and 'reduce' array methods in JavaScript?
-The 'map', 'filter', and 'reduce' methods are used to iterate over an array and perform transformations or computations. The 'map' method creates a new array by applying a function to each element of the original array. 'Filter' applies a conditional statement to each element and returns a new array with elements that meet the condition. 'Reduce' reduces the array to a single value by applying a function that accumulates results.
Can you explain how the 'map' method works with an example?
-The 'map' method applies a function to each element of an array and returns a new array with the results. For example, if you have an array of numbers and you want to create a new array with each number multiplied by 3, you can use 'map' to iterate over the original array and apply the multiplication operation.
How does the 'filter' method differ from the 'map' method?
-While both 'map' and 'filter' iterate over array elements, 'map' transforms each element and returns a new array with all elements, 'filter' only returns elements that meet a specified condition. It does not transform the elements but rather selects a subset of the original array based on the condition.
What is the main difference between 'reduce' and the other two methods?
-Unlike 'map' and 'filter', which return arrays, 'reduce' collapses the array into a single value. It applies a function to each element in the array, accumulating the result in an accumulator variable, which is then returned as the final output.
Can you provide an example of creating a polyfill for the 'map' method from scratch?
-A polyfill for the 'map' method can be created by extending the Array prototype with a new function that iterates over the array elements, applies the callback function, and collects the results in a new array. The polyfill would look something like this: `Array.prototype.myMap = function(callback) { let temp = []; for (let i = 0; i < this.length; i++) { temp.push(callback(this[i], i, this)); } return temp; };`
What is the purpose of the callback function in the 'reduce' method?
-The callback function in 'reduce' is responsible for accumulating the result. It takes four parameters: the accumulator, the current value, the current index, and the array being reduced. The accumulator accumulates the callback's return values; it's the accumulated value previously returned in the last invocation of the callback, or the initial value if provided.
How can you chain methods like 'map' and 'filter' together?
-Chaining methods in JavaScript allows you to use the output of one method as the input for another. For example, you can first filter an array to get elements that meet a certain condition and then map the resulting array to transform those elements further.
What is the difference between using 'map' and a traditional 'for' loop for transforming array elements?
-While both 'map' and a 'for' loop can be used to transform array elements, 'map' is more concise and functional, automatically creating a new array with the transformed elements. A 'for' loop, on the other hand, requires manual array creation and element assignment, which can be more error-prone and less readable.
Can you give an example of how to use 'filter' to get students with marks greater than 60?
-You can use 'filter' to create a new array that only includes students who scored more than 60 marks. The syntax would be something like: `const highMarksStudents = students.filter(student => student.marks > 60);`
How can you combine 'map', 'filter', and 'reduce' to solve more complex array manipulation tasks?
-For complex tasks, you can chain these methods to perform multiple operations in sequence. For example, you might first use 'filter' to select elements based on certain criteria, then 'map' to transform those elements, and finally 'reduce' to aggregate the results into a single value.
Outlines
📚 Introduction to JavaScript Array Methods
This paragraph introduces the importance of JavaScript's array methods 'map', 'filter', and 'reduce' in application development and interviews. The speaker plans to explain each method, create polyfills from scratch, and address common interview questions. The video begins with a demonstration of the 'map' method, showing how to create a new array by transforming each element of an existing array using a callback function. The explanation includes a practical example of multiplying each element of an array by a number and logging the result to the console.
🔍 Deep Dive into 'map' and 'filter' Methods
The speaker continues by contrasting the 'map' and 'filter' methods. 'Map' is used to create a new array by applying a transformation to each element, while 'filter' is used to create a new array with elements that meet a certain condition. The paragraph includes a step-by-step guide on creating a 'myMap' polyfill and demonstrates its functionality with an example. Following this, the 'filter' method is explained with an example of creating a new array that only includes elements greater than a specified value. A polyfill for 'filter' is also created and tested.
🔧 Exploring the 'reduce' Method and Its Polyfill
The 'reduce' method is introduced as a more complex function that condenses an array into a single value by applying a cumulative operation. The paragraph explains the parameters of the 'reduce' method, including the accumulator, current value, index, and array. A polyfill for 'reduce' is created, which involves initializing the accumulator with an initial value and iterating over the array elements to accumulate the result. The functionality of the 'reduce' polyfill is tested with an example that calculates the sum of an array's elements.
🛠 Creating Polyfills from Scratch
The speaker discusses creating polyfills for 'map', 'filter', and 'reduce' from scratch. The process involves adding custom functions to the Array prototype, allowing these methods to be used on any array. The 'myMap' and 'myFilter' functions are explained in detail, with examples of how they iterate over array elements and apply the callback function. The paragraph also includes a demonstration of how to test these custom functions to ensure they work as expected.
🤓 JavaScript Interview Questions and Techniques
This paragraph focuses on common JavaScript interview questions related to array methods. The speaker discusses the difference between 'map' and 'forEach', highlighting that 'map' returns a new array while 'forEach' does not return anything and can be used to modify the original array. The paragraph also covers how to chain methods like 'map' and 'filter' for more complex operations. Practical examples are given, such as transforming an array of student objects to meet specific criteria using 'map', 'filter', and 'reduce'.
📈 Advanced Use Cases and Interview Challenges
The final paragraph presents more complex interview questions that involve combining 'map', 'filter', and 'reduce' methods. The speaker demonstrates how to solve problems such as filtering students based on marks, adding grace marks, and calculating the total marks of eligible students. The paragraph emphasizes the importance of understanding these methods for JavaScript interviews and encourages viewers to practice and master them.
Mindmap
Keywords
💡Array Methods
💡Map
💡Filter
💡Reduce
💡Callback Function
💡Polyfill
💡Iteration
💡Interview Questions
💡Chaining
💡Accumulator
💡Conditional Statement
Highlights
Map, filter, and reduce are essential array methods in JavaScript, often discussed in interviews.
Map creates a new array by applying a function to each element of an existing array.
Filter includes elements in the output array that meet a certain condition.
Reduce collapses an array into a single value through a cumulative computation.
Creating polyfills for map, filter, and reduce helps understand how they work under the hood.
The map function is used to transform elements of an array into a new form without modifying the original array.
Filter allows for conditional logic to determine which elements are included in the resulting array.
Reduce is suitable for calculating a single value, such as a sum, from an array.
The accumulator in reduce holds the accumulated value after each iteration.
Differences between map and for-each are highlighted, such as map's ability to return a new array.
Map supports method chaining, unlike for-each, which does not return an array.
Practical examples demonstrate using map, filter, and reduce to manipulate and analyze student data.
Interview questions often require combining map and filter to solve complex data manipulation problems.
Reduce can be used to calculate the sum of marks for students meeting certain criteria.
Chaining filter after map allows for further refining the data based on additional conditions.
A complex interview question involves adding marks to students and then filtering and summing their scores.
The video provides insights into JavaScript interview questions and encourages viewers to subscribe for more content.
Transcripts
map filter and reduce we all use this
array methods a lot of times while
developing our javascript applications
and these are amongst one of the most
asked questions in javascript interviews
interviewers absolutely love to confuse
candidates by questions like how they
work difference between them creating
these functions from scratch etc so map
filter reduce are basically array
methods that are used to iterate over an
array and perform a transformation or
computation
each may or may not return a new array
based on the result of the function
so in this video i'll be explaining each
one of them one by one make polyfills
for them from absolute scratch and
discuss some commonly asked interview
questions so i've opened vs code over
here with html css and javascript files
and when i go on to run this
we have this window over here
so i'm gonna quickly open the console
because that is where we are gonna see
our output all right so let's start by
discussing each map filter and reduce
separately and this is a very basic
question that interviewers ask on this
topic so first we're gonna discuss what
is map
so the map method is used for creating a
new array from existing one by applying
a function to each one of the elements
of the first array so let me show you if
i go on and type const
numps array and i'm gonna give let's say
one two three
four now what i wanna do is i want to
multiply each of these elements by 5 and
return a new array to me so i can create
a new variable const
multiply
3
and inside of this we're going to type
nums and here map comes in the picture
so i i'm going to type map
and this takes a callback function so
we're going to provide a function over
here and this function takes three
things first is the current element so
it's going to iterate through all of
these elements right so it's going to
take the current element so let's say
i'm going to give this num
and second will be the index that is
this 0
1
2 so
index and the third will be the actual
array
that is this array so we're gonna say
arr
in this case we're not gonna use index
or the array
so what i'm gonna do over here is i'm
gonna go inside and say return num
into
3 and what this will do is it's going to
take each element of this array and
multiply by 3 and return it and it's
going to return a completely new array
inside of this multiply 3. so let's go
on and console.log this
and let's see the output
yep you see we have a completely new
array with all of the elements
multiplied by 3.
now if you would like to see what this
index does is
let's say we add index in this as well
so it should give us result like three
like this
one
two into three plus one something like
that so
let's find out
yep we have 3 7 11 and 15.
so this is how
a map array method works so let's see
what filter is so the filter method
takes each element in an array and it
applies a conditional statement against
it if the conditional returns true the
element gets pushed into the output
array if the condition returns false the
element does not get pushed into the
output array in short filter returns
only those elements from the array which
fulfills the provided criteria so let me
show you so let's say we have const and
what we want to do is we want to only
return the elements which are more than
two so i'm gonna give it more than
to name
and i'll say nums dot filter
inside of this again this is going to
take a callback function
and this will again take those three
things
num
index and the array so num and but in
this case as well we don't need index
and array so i'm just not going to write
them
so return if num is more than 2.
let's console log this more than
two
let's find out
yup you see
we only returned the elements that were
more than two inside of this more than
two array so this is what filter does
and you can clearly notice that its
syntax is similar to map except the
function returns true to keep the
element or false to not return it now
the reduce method is probably most
complicated of all three the reduce
method reduces an array of values down
to just one value just like map and
filter reduce also executes the callback
for each element of the array so it
receives two things so let me show you
so if i write const
sum so what we want over here is we want
to make
we want to calculate the sum of all of
these elements we want to reduce this
array
down to just one value which is going to
be the sum of this array so i'm going to
write const sum equals
nums dot reduce
and now this is gonna take two things as
you can see over here it's gonna take
one callback function and an initial
value
so i'm gonna
write the callback function over here
and the second parameter is gonna be the
initial value so i'm going to keep the
initial value as 0.
now this callback functions parameters
are a little bit different from what map
and filter had so this has an
accumulator
the current value
the index and our array
so what are these accumulator and the
current value so accumulator is
basically the result of the previous
computation right now there is no
computation at the beginning right so
this is going to be zero initially the
current value is the current element of
the array obviously and then we have the
index and the array so what we're going
to do over here is
we're going to return
accumulator plus the current value
so it's going to start by 0 and it's
going to add 1 2 3 4. just like that
it's going to make the sum of this
complete array and return to us
so let me just quickly console log this
so let's see and here you see we get
this 10 as the sum of this array awesome
now don't worry if you're having trouble
understanding them now we are going to
discuss output questions on each one of
them as we move forward in this video
but let's first start with how we can
create
each one of them from absolute scratch
that is their polyfills
so first let's create the polyfill for
map
so i'm gonna write array
dot prototype
dot and i'm gonna give this some custom
name so i'm gonna say let's say my map
and don't worry if you don't know
anything about prototypes i'm gonna
bring a separate video on prototype and
prototypal inheritance etcetera so do
click on subscribe button if you're
excited for that video so what this
prototype is doing is it's adding this
mymap function to the methods of this
array in our current javascript file
so
this will take a function
i'm not going to give this any name
and for the parameters it's going to
take a callback so let me write the map
syntax over here quickly so we have
array.map
and
map takes a callback
which inside of it takes
the current value index and the array so
we're going to reference this and create
the polyfill for our my map function
okay now instead of this this takes a
callback
now
so map returns a completely new error
right so to create a new array we will
need an empty array first so let's
declare
let
temp
to be an empty array and now inside this
since we are going to iterate through
each element of the array we're going to
have a for loop
which will start from 0 go to this dot
length
so i've written this this dot length
over here is because obviously we're
gonna when we use this my map function
we're gonna write something like this
array dot my map so since this is the
part of this
array so when we use this inside of it
it's gonna reference our parent array so
this here means basically the array that
which we are working on now inside of
this since we have this callback
condition right so what we're gonna do
we're gonna say temp
that is this temporary output array
temp dot push
and what are we gonna push we're gonna
push the computation of this callback
i'll say call back and i'm gonna provide
these three things the current element
index and the array
so the current element is this of this
index so i'm going to write
this that is our array and the index i
second one is the index so i'm just
going to write i and the third one is
the actual array so i'm just going to
write this
and now i will return
temp
and that's it this is our custom map
function congrats so let's try this out
and see if it works as expected so this
was the example that we discussed while
understanding the map so let's remove
this dot map over here and i'm going to
use my map polyfill and let's save this
and see
yep it works as expected
great now let's go on and create the
polyfill for filter so to create the
polyfill for filter it's going to be
absolutely same as it was for map so i'm
going to say array dot prototype dot
filter
and it's going to take a call back just
like map
and inside of this since this also
returns an array so i'm gonna have let
temp
empty cool
now again since we are iterating through
each of the values so i'm gonna write
for loop
okay so things are absolutely same up
until this point
so what is the difference between map
and filter
so map basically returns each and every
value and modifies it according to the
condition of the callback right but
filter only returns those values which
satisfy the condition of callback
not each and every element
so in the map we used to do this temp
dot push
and then insert this we gave callback
and the current element index and the
array to it right but we're not going to
do that over here
we're going to first check
if
callback satisfies the condition so
callback will have the current element
that is this
of i
the index
and the current array that is this
and if this satisfies the condition then
we're going to push
the current element that is this of
i just like that and the and in the end
we're gonna return
temp
that's all that's all we need to do
and i'm gonna name this my filter
actually so that it doesn't clashes with
the pre-existing filter function inside
of the array prototype
so here's that example that you
discussed while understanding filter so
let's replace
this filter with my filter and test to
see if it works
which it does cool
let's discuss the polyfill for reduce
okay so the polyfill for reduce it's a
little different from map and function
as you know so it takes two things one
is a callback
and the other is the initial value so
initial
value just like that inside of this
function we're gonna say callback
comma initial value and this callback
has how many things
it has the accumulator
the current value
the index and the array
so we're gonna work according to this
syntax now instead of this
we would first need to initialize the
accumulator so with the initial value so
i'll write where
accumulator
equals
initial value okay so that's done
now next obviously we're going gonna
iterate through all of the elements of
the array so we're gonna need the for
loop now inside of this for loop
so i missed one point while explaining
reduce so what happens if the user fails
to give the initial value so in our case
we gave the initial value as zero right
but what if he fails to give the initial
value any initial value so what happens
is accumulator takes the first element
of the array as the initial value and
the current value is assigned the second
element of the array so we're going to
check over here
accumulator equals
accumulator
we're going to check
if there's anything inside of the
accumulator then that's fine we're going
to go inside of the callback and execute
it
by providing the accumulator the current
value which is this of i
and the index and the current array
that is this
cool
but what if it doesn't have anything
inside of it then we will first go on
and assign it the first element of the
array so we will say this of i
oops i
just like that
and now when it comes to another loop
it's gonna already have the initial
value as the first element of the array
now after this loop ends
it's gonna have the final value of our
reduce function inside this accumulator
so we're gonna just return
accumulator just like that and that's it
this is our polyfill for reduce function
let's test it out so again we have the
example that we used to understand the
reduce so i'm just gonna
replace it with my reduce
save it let's see
yep still got the same output
so i hope you are able to understand how
you can go on and create these functions
from absolute scratch and these are
really important for the javascript
interviews now there's one question
which is really commonly asked in these
javascript interviews that is map versus
4h so this question was asked to me in
my an academy interview on which i have
made a complete video and here is the
clip to that question what is the
difference between map and for each
so to explain this we're gonna take an
array
with let's say two five three four
some random values
now first of all what are map and for
each these both are array functions to
loop through the items of the array so
if i go on and say arr
dot map
and we're gonna provide a call back over
here so just like this
and now we can perform any operation on
this array so let's say return
ar
plus 2. so what this will do is it's
going to return the whole array with two
added to each item of the array it's not
going to modify the original array
whereas if we do this
for each this performs like a normal for
loop but this doesn't return anything
just like map does so if i go on and say
const map result
and
const
for each
result
and go on and console log both of these
now let's go to our browser and open the
console so we get an array in the result
of the map so it returned us the array
but didn't modify the original array so
it returned us a new array with all of
the items
having a plus two
but the for each didn't return us
anything so both of these functions have
a different use case let's say if we
want to modify this array so what i'm
going to do i'm going to take the index
so what this will do is it will modify
the original array so let's say i'm
going to add 3 to it and now i'll
console log this array
this was the array from the map and this
was the modified array which was arr our
original array now this was the first
difference now the second difference is
that you can chain stuff on map so i can
say dot and something we can let's say
if we want to do dot filter and do some
operation inside of this filter so we
can do that with map but in forage since
it doesn't return any array we cannot
chain other methods after it
all right now let's discuss some output
based questions which involve the use of
map filter and reduce so let's save the
interview provided with this array
called students which has the data for
four students with name roll number and
marks inside of each of the object so
the first question that interviewer gave
is that you need to return only the name
of students in capital letters so there
can be multiple approach to this
question you can either use the
traditional for loop or you can use the
for each or you can use a map so let's
see what would have been the case if we
used the traditional for loop we would
have created a new array first of all so
let names
names
we would have ran a for loop
inside this for loop we would have said
names
dot
push we're gonna push only the name of
the student and we will take each of the
element so i'll say i
and take the name and make it to
upper case and that's it and then we
will print this
console.log this names
let's see the output
yep
we get the output that's fine but this
code looks a little messy let's clean
this up by using map
so i'll say const
names and i'm going to make this one
liner so i'll say students
dot map and let's says 2 for the current
element
and i'll says 2 dot
name
name
dot 2 upper case
that's it that's all we needed to do
and we are done with this just one line
of code let's see the output and we get
the same output all right pause if
you're not yet following me on twitter
go to twitter.com push underscore eon or
click the link in the description down
below and hit that follow button right
now
i'm waiting for you
i'm still waiting
okay fine let's continue with the video
now the second output question is return
only the details of those students who
scored more than 60 marks so i want you
to try this yourself and what do you
think which function are we gonna use to
solve this question pause the video
right now and solve it okay i hope you
have solved it yourself so i'm gonna
show you the answer so we will have a
variable called
details
and inside of it i'm going to take
students
dot
filter we're going to use filter
function now we will take s2 and we will
add the condition what was the condition
it has to the marks have to be more than
60. so 2
dot marks
to be more than 60 and that's all that's
all we needed to do to calculate the
answer and let's see the output
we get two
elements of the array and both of these
students had marks more than 60 and
those who didn't have marks more than 60
were filtered out from the array now the
next question can be returned the
details of only those students who have
marks greater than 60 and roll number
greater than 15 so i think it's gonna be
same as the previous question so i'll
write
this
value and instead of it i'll write
students dot
marks
have to be more than 60. okay that's
fine and the other condition is
that roll number has to be greater than
15 so
2 dot roll number has to be greater than
15.
let's see the output for this i'm going
to console.log details
and only one of the students had
marks more than 60 and roll number
greater than 15. now the next question
is we need to calculate the sum of marks
of all of the students
so you already know what we're going to
use here
we're going to use reduce
so reduce we will take the accumulator
and the current value
oops i mean
comma
now here we will just simply say
accumulator plus
the current value
dot marks that is the current element
that is this one and we're going to take
the marks so we took the marks over here
and here you can provide the initial
value as 0.
and let's see const sum equals and i'm
gonna console.log
sum
so let's see
yep we get the sum of all of the marks
of all of the students
great now these questions were really
straightforward now there can be
questions which may involve use of more
than one function that is you may need
to use map or filter together filter or
reduce together so let's see those type
of questions our next question is to
return only names of the students who
scored more than 60.
so we already seen this part
and we already saw this part as well in
we saw this part in map and we saw this
part in filter so we're gonna need to
combine both of them
somehow
filter first of all we're going to
filter out those students which have
less marks than 60 or more marks than 60
sorry i'll say s2
marks oops i mean 2 dot marks has to be
more than 60. that's fine this is gonna
return us all of the students with marks
more than 60. now
as i discussed in my map versus for each
video and i forgot to mention this over
here in this video that all of these
functions map filter and reduce
allows chaining we can chain other
functions in front of these functions
so
the output of this
filter
can be chained by typing dot map or dot
filter or dot reduce so i'm gonna map
through the result of this
condition right here so i will say
s2
and 2 dot name we are only supposed to
return the name
so this should do it let's see names
and awesome so we only got the name of
those students which have scored more
than 60. okay so our last question is a
bit complicated
so this says return total marks for the
students with marks greater than 60
after 20 marks have been added to those
students who scored less than 60. so all
of those students who have marks less
than 60 got a grace of 20 more marks so
20 marks will be added to those students
and after that we are supposed to return
only those students which have
marks greater than 60 after the addition
of 20 marks of course and then for those
particular students we are supposed to
calculate total marks the sum of total
marks of those students so let's see
what is the constant total marks
and i will say
students dot first of all we're gonna do
the map
so inside this map i will take
student
and i will say
if
student
marks are less than 60.
we're going to provide them
a 20 marks grace
so i will says 2 dot marks
and we're going to add
20 to it and then we will return
that particular student that's all let's
see the output for this one
before moving forward
so
these students had less marks than 60
caution and they'll breathe
so
they got 20 marks extra
cool so this one works now we are going
to chain
another function that is filter over
here
and we're going to filter out all those
students
with marks greater than 60. so i'll say
student and student dot marks
greater than 60.
let's see the output now
okay one of the students which had
less marks than 60 got removed and now
we're supposed to return the total marks
for the students so we will chain
another reduce over here to calculate
the sum
so
accumulator and the current value
just like previously i'm going to take
the accumulator and add the current
value
dot max
and provide the initial value as 0
and that's it i think this should do it
let's find out 224 amazing we got the
output so you see these type of
questions can be asked to you during
your javascript interviews and since
you're watching this channel you're
definitely able to crack them so hit the
like on this video if you want me to
create more such awesome javascript
interview videos and the complete
playlist for this javascript interview
series will be in the description down
below and obviously don't forget to
subscribe or your code will give you
errors
浏览更多相关视频
Map, Filter & Reduce EXPLAINED in JavaScript - It's EASY!
How to render LISTS in React 📃
SUPER() in Python explained! 🔴
Crack Your Java Interview With Most-Asked Questions | Java Fundamentals
OOPS Interview Questions and Answers | Object Oriented Programming Interview Questions C#
Higher Order Function | javascript interview series
5.0 / 5 (0 votes)