[英]Calculate quantity of object in Array based on date in Javascript
I have a reportsList
include 1000 object report like this: 我有一个reportsList
包括1000个对象报告,如下所示:
{
"id": 39,
"userId": 3,
"emotion": {
"id": "worried",
"name": "Worried Face",
"colons": ":worried:",
"emoticons": [],
"native": "😟",
"skin": null,
"unified": "1f61f"
},
"title": "Enim consequatur in quia voluptatum.",
"date": "2018-07-14",
"achievement": "Necessitatibus libero voluptas quod autem voluptatum cupiditate hic.",
"plan": "Suscipit molestiae rerum. Nostrum est est quae. Facere amet doloresam.",
"issues": [
"Keeping up with Technology"
],
"description": "Qam iure earum iusto sapiente amet quaerat. Sed ducimus dolor et minus quas qui repudiandae.",
"comment": "Quientore sed aliquid aut dolorum."
}
Now I want to calculate number of emotion based on 4 months: 6, 7, 8, 9 and then count them. 现在,我想基于4个月来计算情感数量:6、7、8、9,然后对它们进行计数。
This is my result that I'm expecting: 这是我期望的结果:
emotions = [20, 30, 40, 50]
How can we implement this one? 我们如何实现这一目标? Please give me some idea. 请给我一些想法。 Thanks! 谢谢!
You can try: 你可以试试:
// untested
// desired months
const months = [6, 7, 8, 9];
// For each of the desired month
const emotions = months.map(month => {
// Filter out the same month object
const array = reportsList.filter(obj => {
// Get the month per data
const objMonth = new Date(obj.date).getMonth() + 1;
// return true if it is the same month
return month === objMonth;
});
// return the array length
return array.length;
});
Something like this I guess: 我猜是这样的:
const emoticonsByMonth = reportsList.reduce((acc, report) => {
const month = new Date(report.date).getMonth();
if (month >= 6 && month <= 9) acc[month - 5] += 1;
return acc;
}, [0, 0, 0, 0]);
getMonth() return the month starting from 0 so Jun would be 5 ... that's why you have to increment at month - 5
and not month - 6
getMonth()返回从0开始的月份,因此Jun将是5 ...这就是为什么您必须在第month - 5
month - 6
而不是第month - 6
递增
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.