Search code examples
javascriptarraysgroupingjavascript-objects

How to group an array of objects by month & year?


I have an array of objects like so:

entries: [  
   {  
      id:1,
      text: "Lorem ipsum",
      timeStamp:"Thu, 01 Jun 2018"
   },
   {  
      id:3,
      text:"Lorem ipsum",
      timeStamp:"Thu, 24 May 2018"
   },
   {  
      id:4,
      text: "Lorem ipsum",
      timeStamp:"Thu, 24 May 2018"
   }
]

Now I'd like to be able to group them into an 'archive' array like so:

archive: [
   {
      monthyear: May 2018,
      entries: 2
   },
   {
      monthyear: June 2018,
      entries: 5
   }
]

Wondering what sort of array functions should I use to get the intended result.


Solution

  • You could use reduce method to group array items by date and toLocaleString method to get month and year.

    const data = [{"id":1,"text":"Lorem ipsum","timeStamp":"Thu, 01 Jun 2018"},{"id":3,"text":"Lorem ipsum","timeStamp":"Thu, 24 May 2018"},{"id":4,"text":"Lorem ipsum","timeStamp":"Thu, 24 May 2018"}]
    
    const result = data.reduce((r, {timeStamp}) => {
      let dateObj = new Date(timeStamp);
      let monthyear = dateObj.toLocaleString("en-us", { month: "long", year: 'numeric' });
      if(!r[monthyear]) r[monthyear] = {monthyear, entries: 1}
      else r[monthyear].entries++;
      return r;
    }, {})
    
    console.log(Object.values(result))