Creating a new array on the basis of dates inside array of objects

February 25, 2023

A common problem many devs face in their daily tasks is how to perform certain actions on their data. There are cases when the data from API is not as we want wanted to be seen on the client. Yesterday one of my colleagues faced the same issue.

 

The problem was that he wanted to show the blog posts on the basis of the months it was written to the user. For example, posts related to Feb should be categorized into one as Feb followed by the year like Feb 2023.

 

Creating an array of posts that are of the same month and adding the month as their category name. So for the beginning, the data from the CMS is coming something like this. We are using Strapi which is an awesome CMS by the way. One should definitely try.

 

code snippet

 

There is a key publishedAt which includes the date of the post. We are simply converting it to Feb 2023 with the help of dayjs again a very much useful library.

 

Now coming to the interesting part of manipulating it according to our needs. We need something like this

 

code snippet

 

For this, we need to map over each object inside the array and find the post date. On the first iteration if the month is coming for the first time simply add the month to the category and blog to the blogs array. On the second iteration if the blog is related to the same month just push the blog to the same blog array of the previous category. If it's a new month then create a new category with the new month name and push the blog into that.

 

There are many solutions to this issue but I found Reduce to be the most useful in this scenario. Because we want to iterate over the array find the same post and reduce it into a new array that has the same post inside one array.

 

If you do not know how to use reduce just go through this explanation on MDN.

 

Now coming to the coding part we are using Reduce on the data and checking if the category for the month is present inside the array we are returning from Reduce. In the first iteration, there will be no category so we just hop over to the else condition. In it, we are just creating the category with the month name and pushing the blog inside the blog's array. So whenever the same month the blog will come it will simply go into the first condition and add that blog into the array.

 

Here is the code for that.

 

code snippet

 

Conclusion

In the end, it's up to you how you approach a particular problem. In my case, I found Reduce to be the most effective approach and I personally recommend using Reduce for these kinds of problems.