Javascript 阵列的垂直平均数
我有以下输入(3xn矩阵) 对象中的数字表示x、y、z坐标。我需要找到他们的平均分。你能帮我做一下算法吗。如何避免手动将索引设置为1,2,3。提前谢谢 我的意见如下:Javascript 阵列的垂直平均数,javascript,typescript,algorithm,matrix,Javascript,Typescript,Algorithm,Matrix,我有以下输入(3xn矩阵) 对象中的数字表示x、y、z坐标。我需要找到他们的平均分。你能帮我做一下算法吗。如何避免手动将索引设置为1,2,3。提前谢谢 我的意见如下: const length = centers.length; return [ centers.map((value) => value[0]).reduce((a, b) => a + b, 0) / length, centers.map((value) => value[1]).red
const length = centers.length;
return [
centers.map((value) => value[0]).reduce((a, b) => a + b, 0) / length,
centers.map((value) => value[1]).reduce((a, b) => a + b, 0) / length,
centers.map((value) => value[2]).reduce((a, b) => a + b, 0) / length
];
编辑:
有了你非常有用的评论,结果是:
centers[0].map((_, index) => centers.map(row => row[index])).map(value => value.reduce((a, b) => a + b, 0) / centers.length);
您可以在第一行使用
.map
,然后使用索引:
centers[0].map((_, index) =>
centers.map(row => row[index]) /*...*/
)
centers[0].map((_, index) =>
centers.map(row => row[index]) /*...*/
)