合并相关的时间序列数据

时间:2019-04-08 10:56:13

标签: javascript data-structures highcharts

鉴于我有两个具有以下结构的对象数组:

  {
      avg: 195.6
      max: 195.6
      min: 195.6
      time: 1552448311000
    }
现在以pp为例:第一个数组具有用于温度传感器的数据,第二个数组具有用于特定发动机负载的数据。要绘制此数据,我需要为绘制的每个点将数据基本上采用以下格式:[负载,温度],所以这是温度与负载的关系图。

如何连接这两个数组,以便仅考虑具有匹配时间戳(一对)的点?我的想法是,我最终可以用一个组合数组做这样的事情:

mergedArray.map(x => [x.load, x.avg])

数据的数据量可能有所不同,例如,温度点可能比负载点多得多,因此我需要首先过滤温度数据,以仅包括其中有匹配时间戳点的点。负载系列。

数据示例:

const temperatureData = [
  {
    avg: 195.6,
    max: 195.6,
    min: 195.6,
    time: '1.1.2019'
  },
  {
    avg: 300,
    max: 300,
    min: 300,
    time: '1.2.2019'
  }
]

const loadData = [
  {
    avg: 195.6,
    max: 195.6,
    min: 195.6,
    time: '1.1.2019'
  }
]

const expected = [{
  avg: 195.6,
  max: 195.6,
  min: 195.6,
  time: '1.1.2019',
  load: 195.6
}]

所以仅获取第一个温度数据,因为它在负载数据中具有匹配的时间戳。

下面是执行此操作的一种简单方法(?),有任何反馈吗?

    // First filter the load by set load filter
    const filteredLoad = load.filter(x => x.avg >= this.props.filter);

    // Collect the timestamps of the filtered load
    const loadTimeStamps = filteredLoad.map(x => x.time);

    const filteredTemperatures = temperaturData.filter(x => loadTimeStamps.includes(x.time))
    .map ((c, i) => {

      if (!filteredLoad[i]) return null;

      return {
        ...c,
        load: filteredLoad[i].avg
      }
    })

1 个答案:

答案 0 :(得分:1)

You can use loops to filter and merge the data:

var newData = [];

for (var i = 0; i < temperatureData.length; i++) {
    for (var j = 0; j < loadData.length; j++) {
        if (temperatureData[i].time === loadData[j].time) {
            newData.push(temperatureData[i]);
            newData[newData.length - 1].load = loadData[j].avg
            j = loadData.length;
        }
    }
}

Live demo: http://jsfiddle.net/BlackLabel/9xsdqwct/

相关问题