【发布时间】:2021-09-09 19:41:40
【问题描述】:
编码新手并尝试解决此问题。我有一个带有这些列标题的 HTML 数据表:
大陆、国家、城市、平均气温
表格数据很长,有很多国家——每个国家有多个条目(即不同的城市)。 我想计算每个国家/地区的平均温度——即将具有相同国家/地区的所有条目的平均温度列相加,然后除以该条目数。
我的目标是最终得到两个数组,它们可以插入到 X 轴为“Country”和 Y 轴为“Avg Temp”的图表中。
我相信以下代码适用于其中一些,但我必须为每个国家(有数百个国家)复制并粘贴此代码。
//read the data from the HTML table
var data = document.getElementById("myTable");
//find array values that match a country and push to new array, then convert array to integer
var canada= [];
var j = 0;
for (j; j < data.rows.length; j++) {
if ( data.rows[j].cells[1].innerHTML.indexOf("Canada") >= 0)
canada.push(data.rows[j].cells[3].innerHTML);
{
//sum the array for a country, find average, and push to a new array to plug into a chart
function getSum(total, num) {
return total + num;
}
myChartData.push(canada.reduce(getSum,0)/canada.length);
我想知道是否可以从 Country 列创建一个包含所有唯一国家/地区值的数组,然后以某种方式为该数组中的每个值执行上述代码。有什么想法吗?或者更好的方法来做到这一点?
【问题讨论】:
-
你知道列表中的所有国家吗?然后,您可以创建一个国家列表并遍历每个值。然后你可以得到每个的平均值。
-
请回复,已经超过45分钟了
标签: javascript arrays dynamic average