Skip to content Skip to sidebar Skip to footer

Javascript Sum Inner Arrays In 3d Nested Arrays

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

Solution 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; }

Solution 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)

Solution 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 }, () =>newArray(arr[0][0].length).fill(0)
);

arr.forEach((array) =>
  array.forEach((rows, row) =>
    rows.forEach((val, col) => (output[row][col] += val))
  )
);

console.log(output);

Solution 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);

Post a Comment for "Javascript Sum Inner Arrays In 3d Nested Arrays"