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);
But this is the sum [1+4+7, 2+5+8, 3+6+9]
.
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; }
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加