Fun Algo Solution Using Reduce

I like to discover new ways to solve problems. There are always many way to solve an algorithm, some better than others. Some are nicer looking, some are a little easier to explain and understand, and some can be solved using JavaScripts .reduce method.

I place reduce in its own category for a reason. Reduce is an alluring iterator. It seems so straight forward, I mean it reduces right? Yes, it reduces, but what is reduces? It seemed like everyone I asked didn’t quite know what was going on, or they did but found it difficult to explain. I myself can’t quite explain it yet, which is why I won't be doing that here. Instead I will lend you a helping hand in the way I learned reduce: through using it.

OK, here's the setup:

Thank you HackerRank

You can find the full explanation to the problem at here. Essentially you have a plane that is sea level, and if you go below that threshold then above it, you’ve gone through a valley. So we need to keep track of the U and D against sea level. We can solve this easily with reduce and a few ifs. Take a look!


We essentially take an array then reduce it to a single sum based on a score, the score being how many time we cross that sea level threshold. Reduce is fun try it out sometime!