Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Computing sum of a 2D array in JavaScript

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));
like image 687
anotherOne Avatar asked Dec 10 '22 23:12

anotherOne


2 Answers

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));
like image 172
Terry Avatar answered Jan 02 '23 04:01

Terry


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

like image 25
AzC Avatar answered Jan 02 '23 06:01

AzC