I'm doing a JavaScript class exercise and I'm really stuck. I have the following array:
let matriz = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
Now, I'm being asked to loop through the entire array, add the values that are in each position of the array, and return a sum. I am very blocked because I am not able to store the sum. My code:
function sumaNumeros() {
matriz.forEach(element => {
console.log(element);
let sumatorioNumeros = 0 + matriz[i][j];
console.log(sumatorioNumeros);
})
}
With the forEach I can go through the array without problem. The problem comes when it comes to storing the values: executing it like this tells me that i and j are not defined, but if I put let sumatorioNumeros+=matriz[i][j]
it it gives me an error, because I imagine that += cannot be done in JavaScript. For now, what I handle best is Java, which can be done perfectly there.
I have made the pseudocode and these are the steps that I think I have to do:
- create function
- traverse array
- I have to save in a variable the sum of going through the different positions of the matrix
- I can finally display the value by console.log or in an alert
It is right there in step 3 where I am blocked. Any suggestion? Thank you very much.
One way it can be solved is using
.reduce()
, since it has 2 dimensions, we can do.flat()
earlier to remove one of those dimensions:If the numbers are going to be consecutive and start with 1, you can use the formula
n*(n+1)/2
, wheren
is thelength
.I'm missing a couple of things:
let sumatorioNumeros = 0 + matriz[i][j]
) anew on each iteration, so previous results are cleared.i,j
not defined, and even if they are, it is a danger because there are times when we do not know the length of the array and if that index does not exist, it will give us an error.That said, what you would need is a couple of changes and go one level down.
Your code would look like this:
Hope this can help you.
A solution you could apply is:
Array.prototype.concat.apply([], matriz) --> array
)array.reduce((a, v) => a + v) --> number
)Example:
References: