javascript - Array 中时间序列对象的移动平均值

标签 javascript html node.js reactjs

[使用 Node 和 ReactJS] 我需要帮助将对象数组中的数据转换为移动平均值。该数据不断更新并按顺序保存日期。

[...{
  x: 2020-02-13T03:31:46.864+00:00
  y: 0.49366917937994004
}...]

需要实现方面的帮助,该实现可以将数据转换为移动平均值,同时保持数据的结构。

我的主要问题是如何执行移动平均线,同时确保日期按顺序保留和使用。

最佳答案

假设您想要创建一个函数,允许您根据不同时间段获取移动平均线,您首先将数据按时间顺序排序,然后根据您想要使用的时间间隔(2 天)获取数组切片、3 天等)。之后,计算每个切片的平均值,然后将所有这些放入一个更大的数组中,根据时间段为您提供一堆移动平均值。该函数可能会通过多种方式崩溃(主要是错误的日期时间输入),因此请持保留态度,并确保在可能的情况下提前实现一些测试。

const testData =  [
  {
    x: '2020-02-13T03:31:46.864+00:00',
    y: 0.4936691793799400
  },
  {
    x: '2020-02-14T03:31:46.864+00:00',
    y: 0.5936691793799400
  },
  {
    x: '2020-02-01T03:31:46.864+00:00',
    y: 0.1936691793799400
  },
  {
    x: '2020-02-06T03:31:46.864+00:00',
    y: 0.2936691793799400
  },
  {
    x: '2020-02-06T03:32:46.864+00:00',
    y: 0.9936691793799400
  }
]


const sortDates = (data) => data.sort((a, b) => new Date(a.x) - new Date (b.x));
const getAverage = (data) => data.reduce((acc, val) => acc + val.y, 0) / data.length;

const computeMovingAverage = (data, period) => {
  const movingAverages = [];
  const sortedData = sortDates(data);

  // if the period is greater than the length of the dataset
  // then return the average of the whole dataset
  if (period > sortedData.length) {
    return getAverage(data);
  }
  for (let x = 0; x + period - 1 < sortedData.length; x += 1) {
    console.log('sortedData.slice(x, x + period)', sortedData.slice(x, x + period))
    movingAverages.push(getAverage(sortedData.slice(x, x + period)))
  }
  return movingAverages;
}

const twoDayMovingAverage = computeMovingAverage(testData, 2);
const threeDayMovingAverage = computeMovingAverage(testData, 3);

console.log('twoDayMovingAverage', twoDayMovingAverage);
console.log('threeDayMovingAverage', threeDayMovingAverage);

/*
twoDayMovingAverage [
  0.24366917937994,
  0.6436691793799401,
  0.74366917937994,
  0.54366917937994
]
threeDayMovingAverage [ 0.49366917937994, 0.59366917937994, 0.6936691793799401 ]
*/

关于javascript - Array 中时间序列对象的移动平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60211628/

相关文章:

javascript - 投资组合图像未在 Mozilla Firefox 中加载

javascript - 作为对象的一部分发送时无法读取 response.json()

javascript - 在 Jquery 中使用 HAML 而不是 HTML 文件是否会更改 onclick 函数的输入?

node.js - 如何在 Windows 上更改 npm 的缓存路径(或完全禁用缓存)?

node.js - 将链接放入 console.log()。 Node .js

javascript - 使用纯 JavaScript 排序表客户端,无需任何库

javascript - 加载程序在进程完成后才会启动

javascript - Bootstrap 4 - 嵌套导航链接仅在第一次打开选项卡内容

html - 修复底部导航栏+修复指向另一个网页的链接

node.js - 如何在 Node Js 应用程序的多个实例之间同步对象