以前从来没有这样做过,所以别对我太苛刻。我有一个相当大的数组:看起来像这样。
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"}]我想按月获得每个优先级的计数。
到目前为止,我已经这样做了:
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);它给出了真/假输出,而不是计数。
2021-06: true
2021-07: false
2021-08: true
2021-09: true
2021-10: false通过删除&& p2,它将计算总数,如下所示:
2021-06: 11
2021-07: 18
2021-08: 11
2021-09: 9
2021-10: 5真的很感谢你的帮助。
发布于 2021-10-14 11:40:14
我迭代每条记录,并在不同的对象中更新计数和月份。这可能会对你有帮助
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);
发布于 2021-10-14 11:45:32
这是另一个解决方案,使用Array.reduce()
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);
https://stackoverflow.com/questions/69569946
复制相似问题