DEV Community

Understanding Array reduce by building it from scratch

Ben Lesh on December 31, 2019

Recently, I was involved in a thread on Twitter, where I mentioned that I also, at one time, found Array reduce challenging to wrap my head around....
Collapse
 
kaul profile image
Keshav Kaul

Thanks for this simple article on reduce! I have a suggestion for changing the map method to a more performant version. Would love to see an article on rxjs's scan method!

The performance of this map is n^2 because we are returning a new copied array inside the reducer method. Isn't this unnecessary immutability? Because we control the initial empty array state, we could mutate this array inside the reducer and still benefit from mutability for the caller of the map method.

Instead of this

Array.prototype.map = function (callback) {
  return this.reduce(
    (result, item, i, source) =>
      [...result, callback(item, i, source)],
    []
  );
}
Enter fullscreen mode Exit fullscreen mode

We could do this -

Array.prototype.map = function (callback) {
  return this.reduce(
    (result, item, i, source) =>
      {
        result.push(callback(item, i, source))
        return result
      },
    []
  );
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
blanka4321 profile image
Lester Dale

I feel I have the potential to be an excellent developer but am not sure what steps to take next to become a Jedi, right now the force is weak with me. Can I get some references to good collaborative open source development I would appreciate this kind people.

Collapse
 
aleksandrhovhannisyan profile image
Aleksandr Hovhannisyan

There are two great things you can do to grow as a software developer, in my opinion: 1) find personal projects that genuinely interest you and that force you to learn new things, and 2) find open source repos that need help.

Doing the latter is admittedly easier than it sounds; what I'd recommend is heading over to GitHub's Explore section to find something relevant to your interests. Even if you don't find a project you can help with, you can at least get your hands dirty with setting up random projects from scratch on your own computer/dev environment.

Collapse
 
evanplaice profile image
Evan Plaice

The beauty of reduce is, it's always pure by default.

I call this rendition "Everything is Reduce" 😁

github.com/vanillaes/absurdum

Collapse
 
emmabostian profile image
Emma Bostian ✨

But when I say "reduce", I mean more like "reduction" in cooking.

I love that quote!