如何在highstocks中绘制图形之前加入两个系列?

时间:2017-03-23 05:11:49

标签: javascript highcharts highstock

我有以下格式的两个javascript数据数组,

Map<City, Set<String>> namesByCity
     = people.stream().collect(groupingBy(Person::getCity, TreeMap::new,                                           
           mapping(Person::getLastName, toSet())));

两个值是{Date,price}。我们无法保证两个系列中的特定日期都有数据可用。我想创建第三个系列,其中包含每天series one: [{date:20170220,price:25},{date:20170221,price:25},......{date:20170322,price:25},{date:20170323,price:55}] series two: [{date:20170220,price:30},{date:20170221,price:28},......{date:20170322,price:24},{date:20170323,price:23}] 的价格。有没有办法在average中获得第三个系列。感谢任何基于javascript的解决方案。

1 个答案:

答案 0 :(得分:1)

我认为这段代码会告诉您所需的内容。

只需循环遍历2个数组并创建第三个数组。我将price键保留为未定义为您的要求。

var s1 = [{date:20170220, price: 25},{date: 20170221, price: 25},{date: 20170322, price: 25},{date: 20170325,price: 55}];
var s2 = [{date: 20170220,price: 30},{date: 20170221,price: 28},{date: 20170323, price: 24},{date: 20170324, price: 23}];

var sortHelper = function(a, b){return a.date - b.date}

//sorting them for sanity
s1.sort(sortHelper);
s2.sort(sortHelper);
var s1Index = 0, s2Index = 0, s3 = [];
while(s1Index < s1.length || s2Index < s2.length){
  if(s1Index >= s1.length){ //for extreme conditions
    for(;s2Index < s2.length; s2Index++){
      s3.push({
        date: s2[s2Index].date
      });  
    }
    break;
  }
  if(s2Index >= s2.length){ //for extreme conditions
    for(;s1Index < s1.length; s1Index++){
      s3.push({
        date: s1[s1Index].date
      });  
    }
    break;
  }
  if(s1[s1Index].date === s2[s2Index].date){
    s3.push({
      date: s1[s1Index].date,
      price: (s1[s1Index].price + s2[s2Index].price) / 2
    });
    s1Index++;
    s2Index++;
  }else if(s1[s1Index].date < s2[s2Index].date){
    s3.push({
      date: s1[s1Index].date
    });
    s1Index++;
  }else if(s1[s1Index].date > s2[s2Index].date){
    s3.push({
      date: s2[s2Index].date
    });
    s2Index++;
  }
}

console.log(s3);

相关问题