Given an array of 3x5, you need to calculate the sum in each column. Tried it this way but I realized that so I'm just trying to calculate the total sum of the array, and moreover, not correct. Please tell me how to calculate exactly the amount in each column a two-dimensional array?

```
mass_two function() {
var n = 3,
m = 5;
var mas = [];
for (var i = 0; i < m; i++) {
mas[i] = [];
for (var j = 0; j < n; j++) {
mas[i][j] = Math.floor(Math.random() * 30) + 1;
sum = 0;
sum += mas[i][j];
}
}
console.log(mas);
console.log(sum);
}
```

asked June 7th 19 at 14:56

3 answers

answered on June 7th 19 at 14:58

It is better if the function would be "not aware" of the size of the array, so versatile.

There is not check that the array is two-dimensional elements that all rows have equal length. And it would be necessary..

Take the first (zero) row and I walk around in the rest, add the values from the corresponding columns:

There is not check that the array is two-dimensional elements that all rows have equal length. And it would be necessary..

Take the first (zero) row and I walk around in the rest, add the values from the corresponding columns:

```
function sum2d(arr) {
var row, col, sum = arr[0].slice();
for( row = 1; row < arr.length; row++) {
for( col = 0; col < sum.length; col++) {
sum[col] += arr[row][col];
}
}
return sum;
}
sum2d([
[1,2,3],
[8,9,0],
])
// [9,11,3]
```

answered on June 7th 19 at 15:00

The type of this?

answered on June 7th 19 at 15:02

Here you amount and along and across, where you have columns and rows - sort it out yourself:

```
var
rows = 3,
cols = 5,
array = [...Array(rows)].map(() => [...Array(cols)].map(() => Math.random() * 10 | 0))
var
sumRows = array.map(n => n.reduce((sum, m) => sum + m, 0)),
sumCols = array[0].map((n, i) => array.reduce((sum, m) => sum + m[i], 0))
```

Find more questions by tags JavaScript