Answer the question
In order to leave comments, you need to log in
Calculate the sum of the elements in each column of a two-dimensional array?
Given a 3x5 array, you need to calculate the sum in each of its columns. I tried to implement it in this way, but I realized that in this way I was just trying to calculate the total amount of the array, and even more so not correctly. Can you please tell me how to calculate the sum in each column of a two-dimensional array?
function mass_two() {
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);
}
Answer the question
In order to leave comments, you need to log in
It's better if the function is "not aware" of the size of the array, it's more universal.
Here I do not check that the array is two-dimensional, that the elements are numbers, that all strings are equal in length. But it should be ..
We take the first (zero) line and go through the rest, add 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]
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question