I am trying to solve a simple problem: given a 2D array of integers (an array made of arrays made of integers) compute the sum of the integers.
For example, given this 2D array:
[
[1, 0, 0],
[1, 1, 0],
[1, 1, 1]
]
the output would be 6.
Here's what I tried:
const array = [
[1, 0, 0],
[1, 1, 0],
[1, 1, 1]
]
const twoDsum = a => a.reduce( (r,x) => r + x.reduce( (s,y) => s + y) );
console.log(twoDsum(array));
As you can see I get three integers, which for me is nonsense.
I also tried the following code to figure out what was going on, but I don't get it
const array = [
[1, 0, 0],
[1, 1, 0],
[1, 1, 1]
]
// this function works as you can see from the logs
const sum = a => a.reduce( (r,x) => r + x );
for(let i = 0; i < array.length; i++) {
console.log(sum(array[i]));
}
// I don't get why this doesn't
const twoDsum = a => a.reduce( (r,x) => r + sum(x) );
console.log(twoDsum(array));
a.reduce( (r,x) => r + sum(x) )lacks its initial value0, hence[1, 0, 0]is used. The first iteration therefore performs[1, 0, 0] + sum([1, 1, 0]), producing a string. Read the documentation. I’d suggest to always provide an initial value.