I used both methods but I am quite confused regarding the usage of both methods.
Is anything that map
can do but reduce
can not and vice versa?
Note: I know how to use both methods I am questioning for main difference between these method and when we need to used.
Best Answer
Both
map
andreduce
have as input the array and a function you define. They are in some way complementary:map
cannot return one single element for an array of multiple elements, whilereduce
will always return the accumulator you eventually changed.map
Using
map
you iterate the elements, and for each element you return an element you want.For example, if you have an array of numbers and want to get their squares, you can do this:
reduce
Using an array as an input, you can get one single element (let's say an Object, or a Number, or another Array) based on the callback function (the first argument) which gets the
accumulator
andcurrent_element
parameters:Which one should you choose when you can do the same thing with both? Try to imagine how the code looks. For the example provided, you can compute the squares array like you mentioned, using
reduce
:Now, looking at these, obviously the second implementation looks better and it's shorter. Usually you'd choose the cleaner solution, which in this case is
map
. Of course, you can do it withreduce
, but in a nutshell, think which would be shorter and eventually that would be better.