首页 > 解决方案 > 数组数组的垂直平均值

问题描述

我有以下输入(3xn 矩阵)

const centers: [number, number, number][] = [[1, 2, 3], [1.2, 2,4, 3,3], [0.9, 2.4, 2.9], [1.1, 2,7, 3,4]];

对象中的数字代表 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]).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);

标签: javascripttypescriptalgorithmmatrix

解决方案


您可以.map在第一行使用 a ,然后使用索引:

 centers[0].map((_, index) => 
   centers.map(row => row[index]) /*...*/
 )

推荐阅读