我一直在思考如何在 Javascript 中实现这个相对简单的操作:
我有一个以这种方式定义的对象列表:
[
{id: 1, region: "America", country:"USA", values:[1,2,3,4] },
{id: 2, region: "America", country:"Canada", values:[3,4,5,6] },
{id: 3, region: "Europe", country:"France", values:[1,2,3,4] },
{id: 4, region: "Europe", country:"Italy", values:[1,2,3,4] },
{id: 5, region: "Europe", country:"Spain", values:[5,9,1,7] },
{id: 6, region: "Europe", country:"Germany", values:[1,6,2,8] },
{id: 7, region: "Europe", country:"Ireland", values:[6,4,6,9]}
]
我正在尝试计算值字段中继续的数字的平均值,并按区域分组。 因此,对于上面的列表,我将再添加两个元素,一个用于美国,一个用于欧洲,其中包含值的平均值:
[
{id: 1, region: "America", country:"USA", values:[1,2,3,4] },
{id: 2, region: "America", country:"Canada", values:[3,4,5,6] },
{id: 3, region: "Europe", country:"France", values:[1,2,3,4] },
{id: 4, region: "Europe", country:"Italy", values:[1,2,3,4] },
{id: 5, region: "Europe", country:"Spain", values:[5,9,1,7] },
{id: 6, region: "Europe", country:"Germany", values:[1,6,2,8] },
{id: 7, region: "Europe", country:"Ireland", values:[6,4,6,9]},
{id: 8, region: "America", country:"avg", values:[2,3,4,5]},
{id: 9, region: "Europe", country:"avg", values:[2.8,4.6,2.8,6.4]}
]
知道如何做吗? 请记住,要聚合的元素数量可能约为 10~15 个,值字段中的数字可能约为 150~200 个 值字段包含所有元素的相同数量的值。 某些值可能为 null,因此在这种情况下我需要计算平均值,因为 null 不为 0!
我可以做很多循环来扫描所有内容并进行计算,但我想知道是否有更简单、更快的方法,同时保持良好的性能。
解释/示例:
美国的第一个平均值计算如下:
(sum of first value of 'values' for each country with region 'America')
-----------------------------------------------------------------------
(number of countries with region 'America')
伪代码:
America.avg.values[0] = (USA.values[0] + Canada.values[0]) / 2 /*(1+3)/2 = 2*/;
America.avg.values[1] = (USA.values[1] + Canada.values[1]) / 2 /*(2+4)/2 = 3*/;
...
最佳答案
您可以使用一个对象来保存元素的总和和计数,并将每个循环值的平均值分配给分组对象。
var data = [{ id: 1, region: "America", country: "USA", values: [1, 2, 3, 4] }, { id: 2, region: "America", country: "Canada", values: [3, 4, 5, 6] }, { id: 3, region: "Europe", country: "France", values: [1, 2, 3, 4] }, { id: 4, region: "Europe", country: "Italy", values: [1, 2, 3, 4] }, { id: 5, region: "Europe", country: "Spain", values: [5, 9, 1, 7] }, { id: 6, region: "Europe", country: "Germany", values: [1, 6, 2, 8] }, { id: 7, region: "Europe", country: "Ireland", values: [6, 4, 6, 9] }];
data.forEach(function (a, i, aa) {
if (!this[a.region]) {
this[a.region] = { sum: [], count: [], values: [] };
aa.push({ id: aa.length + 1, region: a.region, country: 'avg', values: this[a.region].values });
}
a.values.forEach(function (b, i) {
if (b !== null) {
this[a.region].sum[i] = (this[a.region].sum[i] || 0) + b;
this[a.region].count[i] = (this[a.region].count[i] || 0) + 1;
this[a.region].values[i] = this[a.region].sum[i] / this[a.region].count[i];
}
}, this);
}, Object.create(null));
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 对数组数据求平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40130408/