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.
You should make the above table with the given data below.
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.
Let’s take a cup of coffee and dissect the problem.
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();
Now, I want to draw the table.
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.
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)
Lastly, sort them in alphabetical order.
uniqueData.sort((a, b) => b.group < a.group ? 1 : -1);
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.