问题
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].
回答1:
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; }
回答2:
You can use a simple for loop
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 final = [[],[],[]]
for(let i=0; i<arr[0].length; i++){
for(let j=0; j<arr[0][i].length; j++){
for(let k=0; k<arr[0][j].length; k++){
final[i][j] = (final[i][j]||0)+arr[k][i][j]
}
}
}
console.log(final)
回答3:
First create empty output array with 0 values. Use nested forEach loops and fill the output values.
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],
],
];
const output = Array.from({ length: arr[0].length }, () =>
new Array(arr[0][0].length).fill(0)
);
arr.forEach((array) =>
array.forEach((rows, row) =>
rows.forEach((val, col) => (output[row][col] += val))
)
);
console.log(output);
回答4:
A solution where the length of the top level array can be different -- so that maybe it has 4 or 5 grids, and thus results in sums of 4 or 5 values:
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[0].map((row, i) =>
row.map((_, j) => arr.reduce((sum, sub) => sum + sub[i][j]))
);
console.log(data);
来源:https://stackoverflow.com/questions/62234969/javascript-sum-inner-arrays-in-3d-nested-arrays