javascript - 在对象数组中保留每个月的读取计数
问题描述
假设我有一个对象数组:
const sampleArray = [{"read":true,"readDate":2021-01-15T18:21:34.059Z},
{"read":true,"readDate":2021-01-15T18:21:34.059Z},
{"read":true,"readDate":2021-02-15T18:21:34.059Z},
{"read":true,"readDate":2021-04-15T18:21:34.059Z},
{"read":true,"readDate":2021-12-15T18:21:34.059Z}]
我想记录每个月的阅读次数,如果缺少月份,它应该给出 0。
预期 O/P :
[2,1,0,1,0,0,0,0,0,0,0,12] => In jan -2 count, feb - 1 count, april - 1 count, dec - 1 count and rest months there is no read data.
为此,我尝试了:
let invoiceInfoArray = [];
var d = new Date();
var n = d.getMonth();
for (let i = 0; i < sampleArray.length; i++) {
if (sampleArray[i].readDate.getMonth() + 1 == n) {
invoiceInfoArray.push(invoiceInfo[i])
}
}
我还认为好像我检查了每个条件,但这也不可行,因为它会检查特定月份,如果不可用,它将自动插入 0 表示休息,这是不正确的,
for (let i = 0; i < sampleArray.length; i++) {
if (sampleArray[i].readDate.getMonth() + 1 == 1) {
invoiceInfoArray.push(invoiceInfo[i])
} else if (sampleArray[i].readDate.getMonth() + 1 != 1) {
invoiceInfoArray.push(0)
} else if (sampleArray[i].readDate.getMonth() + 1 == 2) {
invoiceInfoArray.push(invoiceInfo[i])
} else if (sampleArray[i].readDate.getMonth() + 1 != 2) {
invoiceInfoArray.push(0)
}
}
我无法就如何实现我的目标形成逻辑,以便我想保持每个月的阅读计数,以及缺少月份的地方应该给出 0。
预期 O/P :
[2,1,0,1,0,0,0,0,0,0,0,1] => In jan -2 count, feb - 1 count, april - 1 count, dec - 1 count and rest months there is no read data.
如果有人需要更多详细信息,请告诉我。任何指导都会很有帮助。
解决方案
创建一个新array
的12
长度并将其readDate
作为Date
对象并从中获取月份getMonth
。
12
您可以使用元素创建一个新数组并预填充0
为
const months = Array(12).fill(0);
// or
const months = new Array(12).fill(0);
const sampleArray = [{
read: true,
readDate: "2021-01-15T18:21:34.059Z"
},
{
read: true,
readDate: "2021-01-15T18:21:34.059Z"
},
{
read: true,
readDate: "2021-02-15T18:21:34.059Z"
},
{
read: true,
readDate: "2021-04-15T18:21:34.059Z"
},
{
read: true,
readDate: "2021-12-15T18:21:34.059Z"
},
];
const months = Array(12).fill(0);
// or
// const months = new Array(12).fill(0);
sampleArray.forEach((obj) => {
const month = new Date(obj.readDate).getMonth();
++months[month];
});
console.log(months);
推荐阅读
- android - 如何在 Mac、Windows 和 Linux 中使用 keytool 为默认调试密钥生成 SHA1、SHA256、MD5?
- excel - 在 VBA 中创建指向特定 powerpoint 幻灯片的单个超链接而不覆盖
- laravel - Laravel Auth 简单 API 总是返回 Unauthorized 401 错误
- javascript - Discord.js 错误 [TOKEN_INVALID]:提供了无效的令牌
- docker - 如何在不知道原始入口点的情况下运行 Docker 预入口点命令?
- c# - 如何在 c# 控制器中将对象作为字符串列表传递?
- javascript - 如何返回输入的动态值?
- c# - ASP.NET Core 3.1 MVC 中的种子数据库 AspNetUserRoles 表
- deep-learning - pytorch 到 Onnx(OCR 模型)
- database - 递归地从文档中获取值