根据索引分组和平均数组值 [英] Group and average array values based on index
本文介绍了根据索引分组和平均数组值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含字符串和整数的二维数组.在GAS中,我想创建一个新数组,该数组对具有公共字符串的数组的整数求平均值.
I have a two-dimensional array that contains strings and integers. In GAS I want to create a new array that averages the integers of arrays that have common strings.
我一直在寻找解决方案,但是我发现的大部分内容都在ES6上,而GAS不支持ES6,其余的我都无法适应我的情况.
I've looked for solutions, but the majority of what I found was on ES6 which is not supported in GAS, and the rest I couldn't adapt to my case.
我尝试使用map,reduce和filter,但找不到合适的解决方案.
I tried to use map, reduce and filter but I couldn't find a proper solution.
下面是数组和所需输出的示例.
Below is an example of the array and the desired output.
function myfunction(){
var array = [
["House1", 1.0, 2.0, 5.0, 1.0],
["House1", 1.0, 4.0, 2.0, 3.0],
["House2", 2.0, 3.0, 3.0, 4.0],
["House2", 5.0, 4.0, 3.0, 4.0],
["House2", 4.0, 5.0, 2.0, 2.0],
["House3", 2.0, 1.0, 4.0, 5.0]]
}
//Desired output
var newArray = [
["House1", 1.0, 3.0, 3.5, 2.0],
["House2", 3.6, 4.0, 2.6, 3.3],
["House3", 2.0, 1.0, 4.0, 5.0]
]
推荐答案
let array = [
["House1", 1.0, 2.0, 5.0, 1.0],
["House1", 1.0, 4.0, 2.0, 3.0],
["House2", 2.0, 3.0, 3.0, 4.0],
["House2", 5.0, 4.0, 3.0, 4.0],
["House2", 4.0, 5.0, 2.0, 2.0],
["House3", 2.0, 1.0, 4.0, 5.0]];
let averageArrays = arrays =>
arrays.reduce((sum, a) => {
a.forEach((v, i) => sum[i] = (sum[i] || 0) + v / arrays.length);
return sum;
}, []);
let grouped = array.reduce((acc, a) => {
acc[a[0]] = acc[a[0]] || [];
acc[a[0]].push(a.slice(1));
return acc;
}, {});
let averages = Object.entries(grouped).map(([name, arrays]) => [name, ...averageArrays(arrays)]);
console.log(averages);
这篇关于根据索引分组和平均数组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文