首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >数组,按月统计具体对象

数组,按月统计具体对象
EN

Stack Overflow用户
提问于 2021-10-14 11:31:03
回答 2查看 38关注 0票数 0

以前从来没有这样做过,所以别对我太苛刻。我有一个相当大的数组:看起来像这样。

代码语言:javascript
运行
复制
var data = [
    {"id": "1", "start_date":"2018-05-15 11:25:00", "priority": "P1"},
    {"id": "2", "start_date":"2019-05-15 11:25:00", "priority": "P2"},
    {"id": "3", "start_date":"2020-05-15 11:25:00", "priority": "P3"}]

我想按月获得每个优先级的计数。

到目前为止,我已经这样做了:

代码语言:javascript
运行
复制
var result = [];


   result = data.reduce((r, {start_date, priority}) => {
     var p2 = priority === 'P2';
     var key = start_date.slice(0, 7);
     r[key] = (r[key] || 0) + 1 && p2;
     return r;
    }, {});

    console.log(result);

它给出了真/假输出,而不是计数。

代码语言:javascript
运行
复制
2021-06: true
2021-07: false
2021-08: true
2021-09: true
2021-10: false

通过删除&& p2,它将计算总数,如下所示:

代码语言:javascript
运行
复制
2021-06: 11
2021-07: 18
2021-08: 11
2021-09: 9
2021-10: 5

真的很感谢你的帮助。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-10-14 11:40:14

我迭代每条记录,并在不同的对象中更新计数和月份。这可能会对你有帮助

代码语言:javascript
运行
复制
const data = [
    {"id": "1", "start_date":"2018-05-15 11:25:00", "priority": "P1"},
    {"id": "2", "start_date":"2019-05-15 11:25:00", "priority": "P2"},
    {"id": "3", "start_date":"2020-05-15 11:25:00", "priority": "P3"}
];

const priorityCount = {}

data.forEach(record => {

  const date = (new Date(record.start_date));
  const monthYear = `${date.getFullYear()}-${(date.getMonth() + 1)}`;
  
  // Checking the year and month already exist, If not creating new
  if (!priorityCount[monthYear]) {
    priorityCount[monthYear] = {
      P1: 0,
      P2: 0,
      P3: 0
    };
  }
  
  // Updating the count of the relevant priority (P1/P2/P3)
  priorityCount[monthYear][record.priority]++;
  
});

console.log(priorityCount);

票数 0
EN

Stack Overflow用户

发布于 2021-10-14 11:45:32

这是另一个解决方案,使用Array.reduce()

代码语言:javascript
运行
复制
var data = [{
    "id": "1",
    "start_date": "2018-05-15 11:25:00",
    "priority": "P1"
  },
  {
    "id": "2",
    "start_date": "2019-05-15 11:25:00",
    "priority": "P2"
  },
  {
    "id": "3",
    "start_date": "2020-05-15 11:25:00",
    "priority": "P3"
  },
  {
    "id": "4",
    "start_date": "2020-05-15 11:25:00",
    "priority": "P3"
  },
  {
    "id": "5",
    "start_date": "2018-05-15 11:25:00",
    "priority": "P3"
  },
]

const byMonthByPrio = data.reduce((prevVal, curVal) => {
  const out = prevVal;
  const {
    start_date,
    priority
  } = curVal;
  const yearMonth = start_date.slice(0, 7);
  if (!out[yearMonth]) {
    out[yearMonth] = {};
  }
  if (!out[yearMonth][priority]) {
    out[yearMonth][priority] = 1;
  } else {
    out[yearMonth][priority]++;
  }
  return out;
}, {});

console.log(byMonthByPrio);

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69569946

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档