r/learnjavascript • • Mar 24 '20

Array Reduce Explained in 80 Seconds

https://youtu.be/lxT4LZdtJrU
70 Upvotes

25 comments sorted by

View all comments

1

u/philipjfrizzle Mar 24 '20

Reduce can do much more than sum. I like to think of reduce as a sandbox where you can basically do anything you want with an array.

You will always reduce your array down to a single item, but that item doesn’t just have to be an integer. It could be an object or another array.

Often times when I have to operate on two arrays, I like to use reduce to create an object with the info I need from one of the arrays. Then with the other array, I iterate thru it, with a .forEach for ex. I use the object I just created from the other array to lookup the values needed. This keeps the operation linear, as opposed to a quadratic operation with a nested loop.