如何从一个数组中找到平均价格,通过从其他数组中交叉到过去30天?javascript



我有这两个数组,一个包含时间段,第二个包含每个时间段的价格。

如何输出过去30天、60天等的平均价格?

time[
'2021-01-14', '2021-02-08', '2021-02-16',
'2021-02-16', '2021-02-17', '2021-02-22',
'2021-02-26', '2021-02-28', '2021-04-07',
'2021-04-25', '2021-04-26', '2021-05-10',
'2021-05-11', '2021-05-13', '2021-05-15',
'2021-05-16', '2021-05-24', '2021-06-09',
'2021-06-14', '2021-06-14', '2021-06-17',
'2021-06-19', '2021-06-20', '2021-07-15',
'2021-07-17', '2021-07-17', '2021-07-19',
'2021-07-19', '2021-08-02'
]
prices[
79999, 69999, 76641, 76506, 79999,
69999, 64999, 69999, 79999, 72500,
69999, 72500, 77449, 77433, 77684,
79999, 69999, 79999, 69999,    -1,
69999,    -1, 69999, 74999, 69999,
74999, 69999, 74999, 64999
]

这里我使用map()组合这两个数组,并将时间放入一个Data对象。我创建一个Date对象并将其减少30天。我使用filter()过滤组合数组,并使用reduce()计算价格之和。

var time = [
'2021-01-14', '2021-02-08', '2021-02-16',
'2021-02-16', '2021-02-17', '2021-02-22',
'2021-02-26', '2021-02-28', '2021-04-07',
'2021-04-25', '2021-04-26', '2021-05-10',
'2021-05-11', '2021-05-13', '2021-05-15',
'2021-05-16', '2021-05-24', '2021-06-09',
'2021-06-14', '2021-06-14', '2021-06-17',
'2021-06-19', '2021-06-20', '2021-07-15',
'2021-07-17', '2021-07-17', '2021-07-19',
'2021-07-19', '2021-08-02'
];
var prices = [
79999, 69999, 76641, 76506, 79999,
69999, 64999, 69999, 79999, 72500,
69999, 72500, 77449, 77433, 77684,
79999, 69999, 79999, 69999,    -1,
69999,    -1, 69999, 74999, 69999,
74999, 69999, 74999, 64999
];
var combined = time.map((d,i) => {return {date: new Date(d), price: prices[i]}});
//var d = new Date();
// for the purpose of this fixed set of date/price this code will have a fixed "now"-date instead of a future date:
var d = new Date('2021-08-04');
d.setDate(d.getDate()-30);
var filtered = combined.filter(item => item.date.getTime() > d.getTime());
console.log('Should return 6 objects when d = 2021-08-04:', filtered.length);
var priceSum = filtered.reduce((accumulator, item) => {return accumulator + item.price}, 0);
console.log('Should return 429994:', priceSum);

您可以通过从固定日期定义另一个日期对象来调整时间范围,例如:

var d = new Date('2021-08-01');
console.log(d);
d.setDate(d.getDate()-60);
console.log(d);

如果您想要prices数组中最近15个值的平均值:

prices.slice(-15).reduce((a, b) => (a + b)) / 15;

解释:

  • prices.slice(-15)创建一个包含prices数组
  • 的最后15个值的数组
  • .reduce((a, b) => (a + b))返回这些值的和
  • 除以15得到平均值。

N。B:-1值会扰乱结果

得到最后N个你想用slice得到的平均价格

用reduce对它们的值求和

function averagePrice(lastDayCount){
if (lastDayCount <= prices.length){
let lastPrices = prices.slice(prices.length - lastDayCount); 

const totalPrice= lastPrices.reduce(function(subtotal, p) {
const tmp= subtotal+ p;
return tmp;
}, 0);  
return totalPrice / lastDayCount;
}
return 0;

}

最新更新