【问题标题】:What is the best way to get weekly and monthly data from an array of dates?从日期数组中获取每周和每月数据的最佳方法是什么?
【发布时间】:2020-03-23 08:08:36
【问题描述】:

我必须在图表中显示注册用户的每日/每周/每月计数。这是我从后端获得的数据。现在我需要根据视图类型循环遍历数组。 我有这样的数据:

[
  {
    "date": "2019-10-28",
    "count": 0
  },
  {
    "date": "2019-10-29",
    "count": 4
  },
  {
    "date": "2019-10-30",
    "count": 5
  },
  {
    "date": "2019-10-31",
    "count": 2
  },
  {
    "date": "2019-11-01",
    "count": 0
  },
  {
    "date": "2019-11-02",
    "count": 6
  },
  {
    "date": "2019-11-03",
    "count": 0
  },
  {
    "date": "2019-11-04",
    "count": 0
  },
  {
    "date": "2019-11-05",
    "count": 0
  },
  {
    "date": "2019-11-06",
    "count": 0
  },
  {
    "date": "2019-11-07",
    "count": 0
  },
  {
    "date": "2019-11-08",
    "count": 0
  },
  {
    "date": "2019-11-09",
    "count": 0
  }
]

如果是每周视图类型,那么我需要得到类似这样的结果:

[
  {
    "week": 44,
    "count": 15
  },
  {
    "week": 45,
    "count": 13
  },
  {
    "week": 46,
    "count": 3
  },
  {
    "week": 47,
    "count": 13
  }
]

如果是每月,那么我需要得到类似这样的结果:

[
  {
    "10": 100,
    "count": 15
  },
  {
    "11": 45,
    "count": 13
  },
  {
    "12": 460,
    "count": 3
  }
]

使用图书馆时刻,我可以获得这样的周数:

array.forEach((item, index) => {
   var weeknumber = moment(item.date).week();
   console.log("Week ", weeknumber);
})

我不确定获得所需结果的最佳方式和最佳方法。 有什么建议吗?谢谢!

【问题讨论】:

    标签: javascript arrays object foreach momentjs


    【解决方案1】:

    您需要处理数据并准备通用逻辑以将数据转换为正确的格式。

    您可以使用groupByforEach 以及reduce 方法来准备数据,如下例所示

    演示:https://repl.it/@abhirathore2006/PrepareDataForCharts

    const _ = require('lodash');
    // use your dataset
    let data = [
      {
        "date": "2019-10-28",
        "count": 0
      },
      {
        "date": "2019-10-29",
        "count": 4
      }
    ];
    
    // prepare data beforehand to save re-calculations
    data.forEach(d=>{
      d.dateObj = new Date(d.date)
    });
    
    // this method will sum all the counts in given group
    function buildData(data, keyName ){
      let result = []; 
      _.forEach(data, (val, key)=>{
        let totalCounts  = val.reduce((acc, curr)=>{
            return acc + curr.count;
        }, 0)
        result.push({[keyName]:key, count:totalCounts})
      })
      return result;
    }
    
    // this will group data by given output of date method
    function groupAndBuild(data, dateMethod, groupKey) {
      let groupedData = _.groupBy(data, (d)=>{
        return d.dateObj[dateMethod]()
      })
      return buildData(groupedData, groupKey)
    }
    
    // use moment-js or other library to get week number
    // and replace dateObj with moment object
    console.log(groupAndBuild(data,'getMonth','month'))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-08
      • 2021-06-11
      • 1970-01-01
      • 2014-08-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多