使用Javascript和/或jQuery将每周数据转换为月数据

时间:2017-10-20 15:48:00

标签: javascript jquery

我有两个相互关联的数组。 Array A代表每周日期,Array B代表每周价格。每个星期五新数据都会通过API发布并推送到这些数组中,因此有些月份有5个元素(即Jan),而有些月份只有4个元素(即2月)。见下面的例子。

Array A

["2003-01-03", "2003-01-10", "2003-01-17", "2003-01-24", "2003-01-31", "2003-02-07", "2003-02-14", "2003-02-21", "2003-02-28", etc..]

Array B

["5.85", "5.95", "5.97", "5.91", "5.90", "5.88", "5.86", "5.84", "5.79", etc..]

代码:

var ajx = $.getJSON(api, function(data) {                 
   for (var i =0; i <= data.count -1; i++){
      $("#table").append("<tr> <td>" + data.observations[i].date + "</td> <td>" + data.observations[i].value + "</td>  </tr>");
      xaxis.push(data.observations[i].date) //Array A - weekly (default state)
      yaxis.push(data.observations[i].value) //Array B - weekly (default state)
      }

我如何将其转换为“月度”和“年度”数组?

1 个答案:

答案 0 :(得分:2)

您可以使用array#reduce根据年份和每年内部对数据进行分组,您可以总结每个月的价格。

const arrayA = ["2003-01-03", "2003-01-10", "2003-01-17", "2003-01-24", "2003-01-31", "2003-02-07", "2003-02-14", "2003-02-21", "2003-02-28"],
      arrayB = ["5.85", "5.95", "5.97", "5.91", "5.90", "5.88", "5.86", "5.84", "5.79"];

let result = arrayA.reduce(function(res, date, index){
  let [year, month, day] = date.split('-');
  let price = arrayB[index];
  if(year in res){
    if(month in res[year]) {
      res[year][month].price = 
          ((res[year][month].price * res[year][month].count) + +price)/(res[year][month].count+1);
      res[year][month].count += 1;
      
    } else {
      res[year][month] = {price : +price, count : 1};
    }
  } else {
    res[year] = {[month]: {price : +price, count :1}};
  }
  return res;
}, Object.create(null));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }