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));
Make sure you provide the initialValue
(the second positional argument) explicity as 0
for the summation to work. Otherwise the first element will be used, which is [1,0,0]
, which will be converted to a string 1,0,0
:
A value to use as the first argument to the first call of the callback. If no initialValue is supplied, the first element in the array will be used as the initial accumulator value
See working example here:
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, 0), 0);
console.log(twoDsum(array));
If you are just trying to get the sum then why not just flatten the array first?
const arr = [
[1, 0, 0],
[1, 1, 0],
[1, 1, 1]
]
const flatArr = arr.flat()
flatArr
should now be [1, 0, 0, 1, 1, 0, 1, 1, 1]
you should now be able to use the normal reduce
you'd expect to use
const sum = flatArr.reduce((acc, value) => acc += value, 0);
sum
should now be 6
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With