gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 02:53:12 25 4
gpt4 key购买 nike

我有两个彼此相关的数组。 Array A 保存每周日期,Array B 保存每周价格。每个星期五都会发布新数据并通过 API 推送到这些数组中,因此有些月份有 5 个元素(即一月),而有些月份只有 4 个元素(即二月)。请参阅下面的示例。

数组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..]

数组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)
}

我怎样才能将其转换为“每月”和“年度”数组?

最佳答案

您可以使用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; }

关于javascript - 使用 Javascript 和/或 jQuery 将每周数据转换为每月数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46852737/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com