Finding Mode — Javascript

This week I finally decided to see if I could still write Javascript. And not use for loops…

Photo by Greg Rakozy on Unsplash

Over the past 6 months I’ve been flip flopping between taking my career down the path of UX/UI design or front-end development¹.

Having learned the basics of coding when for loops with i++ counters (circa 2006–2010 ish?) were the norm, there’s quite a bit of catch up to do. Especially in the Javascript world.

Bye bye for loops — hello map(), reduce() and filter()

Over the week I’ve solved about 20 beginner code challenges. Some more elegantly than others. Knowing that writing for loops is now considered “bad practice” (validated by talking to pro devs) I had to break old habits.

Naturally I just started using forEach() 😉

And then I came across people talking about using map(), reduce(), and filter(). It took a bit to wrap my mind around these methods, but I forced myself not to use forEach(). There was some 😕 😖 and 😡. And sometimes I used forEach() just to get on with it.

By the time I got to this MeanMode challenge² I found on coderbyte I might have reached some sort of Javascript clarity.

Finding Mode — forEach() way

If you forgot/didn’t know: the mode is the value that occurs most frequently in a given set of data. Although to simplify things I did make a few assumptions, which are in the code comments.

This is the forEach way that I threw together, it can definitely be simplified, but it works. I feel meh about it.

Using forEach() to find mode

Find Mode — using reduce()

After waking up the next day with a clear head and a 😺 pawing my face. I pulled together everything I learned this week and came up with this. Pretty proud of this one ✌️. Since I’m pretty fresh still, do let me know if there’s a better way.

Using reduce() to find mode

Will I keep going with Javascript next week? 🤷‍

Notes:

1: Neither one of these directions is a natural progression from my previous path.
2: If you can’t access the full challenge I found it on someone’s github here.

Like what you read? Give Nancy Huynh a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.