anotherOne
anotherOne

Reputation: 1573

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));

Upvotes: 4

Views: 1989

Answers (7)

Michael Geary
Michael Geary

Reputation: 28850

I am old school, so I would just write a couple of loops. Super easy to code, works the first time with no debugging, and I think it's the easiest solution to understand:

const twoDsum = matrix => {
    let sum = 0;
    for( const row of matrix ) {
        for( const cell of row ) {
            sum += cell;
        }
    }
    return sum;
};

console.log(
    twoDsum(
        [
            [ 1, 0, 0 ],
            [ 1, 1, 0 ],
            [ 1, 1, 1 ]
        ]
    )
);

Upvotes: 2

user6386114
user6386114

Reputation:

Using Array.prototype.forEach().

const array = [
  [1, 0, 0],
  [1, 1, 0],
  [1, 1, 1],
];

const twoDsum = (a) => {
  let total = 0;
  a.forEach(arr => {
    arr.forEach(num => {
      total += num;
    });
  });
  return total
};

console.log(twoDsum(array));

Upvotes: 1

AzC
AzC

Reputation: 71

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

Upvotes: 2

Nina Scholz
Nina Scholz

Reputation: 386560

You could take a recursive approach and check the item if it is an array.

const
   addArray = (s, v) => s + (Array.isArray(v) ? v.reduce(addArray, 0) : v),
   data = [[1, 0, 0], [1, 1, 0], [1, 1, 1]],
   sum = data.reduce(addArray, 0);

console.log(sum);

Upvotes: 1

Talmacel Marian Silviu
Talmacel Marian Silviu

Reputation: 1736

I would suggest instead of doing the reduce twice just use flat method first:

const array = [
[1, 0, 0],
[1, 1, 0],
[1, 1, 1]
]

const twoDsum = a => a.flat().reduce((acc,val) => acc + val);

console.log(twoDsum(array));

Upvotes: 1

Rojo
Rojo

Reputation: 2869

You can instead use .flat() and use the original equation.

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.flat().reduce( (r,x) => r + x );

console.log(twoDsum(array));

Upvotes: 1

Terry
Terry

Reputation: 66103

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));

Upvotes: 5

Related Questions