gpt4 book ai didi

javascript - 我有一百年每个月的温度数据。如何计算每年的平均气温?

转载 作者:行者123 更新时间:2023-11-30 09:45:13 26 4
gpt4 key购买 nike

我知道这是一个菜鸟问题,对此深表歉意。但是我有以下格式的数据列表:

{
"Year": 1881,
"Jan": -8,
"Feb": -13,
"Mar": 2,
"Apr": -2,
"May": -3,
"Jun": -27,
"Jul": -5,
"Aug": -1,
"Sep": -8,
"Oct": -18,
"Nov": -25,
"Dec": -14,
"J-D": -10,
"D-N": -11,
"DJF": -13,
"MAM": -1,
"JJA": -11,
"SON": -17
},
{
"Year": 1882,
"Jan": 10,
"Feb": 10,
"Mar": 2,
"Apr": -19,
"May": -17,
"Jun": -24,
"Jul": -9,
"Aug": 5,
"Sep": 0,
"Oct": -21,
"Nov": -20,
"Dec": -24,
"J-D": -9,
"D-N": -8,
"DJF": 2,
"MAM": -11,
"JJA": -9,
"SON": -14
},

等等

我想计算每年的平均气温。有超过100年。最简单的方法是什么?将它们放在数组中,然后手动计算它们会花费太长时间。即便如此,我也不知道如何分配每年的平均温度。我可以用什么方式编写这段代码?我正在使用 Javascript。

最佳答案

首先,您需要一个键数组来表示月份(这样您就可以忽略所有其他数据)

let months = ['Jan', 'Feb', 'Mar', ...];

然后,假设您的数据在实际数组中,您可以使用 reduce operation (好吧,两个 reduce 操作)来生成年均值的 map

let years = [{"Year":1881,"Jan":-8,"Feb":-13,"Mar":2,"Apr":-2,"May":-3,"Jun":-27,"Jul":-5,"Aug":-1,"Sep":-8,"Oct":-18,"Nov":-25,"Dec":-14,"J-D":-10,"D-N":-11,"DJF":-13,"MAM":-1,"JJA":-11,"SON":-17},{"Year":1882,"Jan":10,"Feb":10,"Mar":2,"Apr":-19,"May":-17,"Jun":-24,"Jul":-9,"Aug":5,"Sep":0,"Oct":-21,"Nov":-20,"Dec":-24,"J-D":-9,"D-N":-8,"DJF":2,"MAM":-11,"JJA":-9,"SON":-14}];

let months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

let averages = years.reduce((avgs, year) => {
let sum = months.reduce((avg, month) => avg + year[month], 0);
avgs[year.Year] = sum / months.length;
return avgs;
}, {});

document.write('<pre>' + JSON.stringify(averages, null, ' ') + '</pre>');

关于javascript - 我有一百年每个月的温度数据。如何计算每年的平均气温?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39135030/

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