Getting the square with reduce()

But reiterating what the other guys said above, filter and map would be far easier to understand in this situation.

reduce, while powerful, is seldom legible outside of a few common operations like summing an array of numbers.

1 Like

Yeah, reduce to me is semantically correct when you are reducing to a single value, like summing. In general, I prefer to use the method whose implication is closest to what I am doing. Here, we are mapping and filtering. Someone could argue that doing it in two steps is a little less efficient (O(2n) instead of O(n)), but it is highly unlikely to make a real difference and the loss in readability outweighs the imperceptible (if that) gain in performance.

1 Like

I was able to understand how to solve this problem with map and filter but reduce function still confuses me a little bit. I can follow what is being done when I read a reduce function but when it comes to writing one on my own, I find it challenging. Hope this is normal for newbies.

1 Like

Very. Of all the Array methods, it is the one that causes the most confusion. I once had to explain how it works to a senior dev - seriously.

My suggestions for learning the prototype methods is to write your own functions. Write your own “myMap” function that accepts the array and the callback and uses a loop to do what the map method does. Then do it for filter and find. Then see if you can make a reduce. Then (if you want) see if you can build the other methods using just reduce.

Or just spend some time with reduce. I’m sure there are a lot of youtube videos out there - watch 10 of them. Then build some code. reduce is a weird one until you get the hang of it, then it is obvious and easy. But yeah, until it “clicks”, it just seems really weird.

3 Likes

If you want to use reduce method ,then you have to mention extra parameter for initial value and must mention your desired value like array.reduce(callback function,initial value)

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.