首页 > 解决方案 > 在对象数组中保留每个月的读取计数

问题描述

假设我有一个对象数组:

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.

如果有人需要更多详细信息,请告诉我。任何指导都会很有帮助。

标签: javascriptnode.js

解决方案


创建一个新array12长度并将其readDate作为Date对象并从中获取月份getMonth

12您可以使用元素创建一个新数组并预填充0

const months = Array(12).fill(0);
// or
const months = new Array(12).fill(0);

阅读有关Array填充

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


推荐阅读