如何按月分组对象数组一年?

时间:2018-06-07 16:39:44

标签: javascript arrays grouping javascript-objects

我有一组像这样的对象:

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"
   }
]

现在我希望能够将它们分组到一个'存档'像这样的数组:

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

想知道我应该使用什么类型的数组函数来获得预期的结果。

1 个答案:

答案 0 :(得分:2)

您可以使用reduce方法按日期和toLocaleString方法对数组项进行分组,以获得月份和年份。



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))