Javascript对3d嵌套数组中的内部数组求和 [英] Javascript sum inner arrays in 3d nested arrays

查看:37
本文介绍了Javascript对3d嵌套数组中的内部数组求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个3d数组,第一级数组可以有一个到很多项(数组)。每个内部数组的长度都是固定的,其元素也是固定长度的数组。在下面的示例中,长度分别为3和3。我想对各个内部数组求和[1 + 1 + 1,2 + 2 + 2,3 + 3 + 3]。输出应该是具有3 x 3形状的2d数组。

I have a 3d array, the first level array can have one to many items (arrays). Each inner array has a fixed length, and its elements are also arrays of fixed length. In the example below length 3 and 3 respectively. I would like sum the respective inner arrays, [1+1+1, 2+2+2, 3+3+3]. The output should be a 2d array with a 3 x 3 shape.

let arr = [
  [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
  ],
  [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
  ],
  [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
  ],
];

//expected output = [[3,6,9],[12,15,18],[21,24,27]]  

我尝试了许多方法,但是我能得到最好的方法:

I have tried many approaches the but the best I can get:

let arr = [
  [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
  ],
  [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
  ],
  [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
  ],
];
let data = [];

arr.forEach((e) => {
  data.push(e.reduce((r, a, i) => a.map((b, j) => r[j] + b)));
})

// returns [[12, 15, 18], [12, 15, 18], [12, 15, 18]]
console.log(data);

但这是总和 [1 + 4 + 7,2+ 5 + 8、3 + 6 + 9]

推荐答案

您可以减少外部数组,因为此维度映射到2d数组的值上。

You could reduce the outer array, because this dimension is mapped over the values for the 2d arrays.

let array = [[[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[1, 2, 3], [4, 5, 6], [7, 8, 9]]],
    sum = array.reduce((a, b) => b.map((x, i) => x.map((v, j) => a[i][j] + v)));

console.log(sum); // [[3, 6, 9], [12, 15, 18], [21, 24, 27]]

.as-console-wrapper { max-height: 100% !important; top: 0; }

这篇关于Javascript对3d嵌套数组中的内部数组求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆