Common javascript problem in real life

Hyo
dooboolab
Published in
3 min readFeb 18, 2020

I’d like to share a common javascript problem in practice which most js or ts programmers will face.

Our goal today is to build the below table.

Figure 1: Goal for today

You should make the above table with the given data below.

Figure 2: Test data to draw the table
Figure 3: Image from https://www.channelpartnersonline.com/2019/09/23/k2-expands-partner-program-with-solution-showcase/

I am going to share my solution in the below paragraph, but I recommend all of you to try out yourself before looking at my approach since there are many ways to solve the problems and also it may help you to improve your problem-solving skills.

Figure 4: My favorite coffee

Let’s take a cup of coffee and dissect the problem.

Figure 5: First goal is to get the date range

Followed by the document, the Set object lets you store unique values of any type, whether primitive values or object references. Retrieving dates as an array from the data then initializing Set instance will give a unique array of dates.

const uniqueDates = [...new Set(data.map((item) => item.date))];
uniqueDates.sort();
Figure 6: Result for above code

Now, I want to draw the table.

Figure 7: What I focus on now

We have multiple data objects with the same group name so I want to combine them and sum up the values of each visitor.

I chose to use Map data structure since this is very essential to group things up with the key value. Therefore, I’ve created Map and loop the given data with forEach statement and set map when the value doesn’t exist or add values.

Figure 8: Filtering unique data with `Map`
Figure 9: The result of figure 8

Since I need each rate for visitors, I’ll use reduce function to find all visitors count.

const allVisitors = data.reduce((a, b) => a + (b.visitors || 0), 0)
Figure 10: Getting additional `rate` and `min` values that are shown in table

Lastly, sort them in alphabetical order.

uniqueData.sort((a, b) => b.group < a.group ? 1 : -1);
Figure 11: Final result

Now, we have all the data to draw the table 🎉. The solution is posted in the thread.

Thanks for reading and please come up with a better solution and share it if you think you have one! You may share yours in current gist.

--

--