javascript - 数组数组的垂直平均值
问题描述
我有以下输入(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);
解决方案
您可以.map
在第一行使用 a ,然后使用索引:
centers[0].map((_, index) =>
centers.map(row => row[index]) /*...*/
)
推荐阅读
- json - jq:基于现有的 json 创建新的 json 并使用 if else
- python - python django global-ish 类实例
- metadata - DCMI,RDF - 基数和出现
- javascript - 类型错误:uuidv4 不是函数
- javascript - 如何在 Chart.js 3 中更改时间序列图表上的标签和网格线位置?
- c# - 在 .Net 中序列化和反序列化 C# 用户定义的类
- python - discord.py 如何在 API 请求中用 %20 替换空格
- python - 在 for 循环中将一维数组转换为二维
- python - 如何捕获从某个字符串开始并从某行结束然后存储到列表中的字符串
- arrays - 是否可以实现修改声明为不可分配的数组的子例程?