-1

I have created a two dimensional array from a Google spreadsheet.
Logger.log shows it as this:

[ [-4.0], [-1.0], [4.0], [2.0], [1.0], [3.0] ]

All I am trying to do is to sum the 6 elements shown above to return the correct total of 5.0

I have tried using the reduce() method on the array which Logger.log then shows as:

[ -4.0, -1.0, 4.0, 2.0, 1.0, 3.0 ]

But I just cannot figure out how to sum the six elements despite much Googling. This must be childishly simple - please could someone help this Apps Script novice?

Moggy
  • 1
  • 4

1 Answers1

0

Thank you for the responses. What worked for me was to flatten the two-dimensional array first, before using reduce().

The two-dimensional array before flattening shows in Logger.log as this: [ [-4.0], [-1.0], [4.0], [2.0], [1.0], [3.0] ]

and after flattening, it shows like this in Logger.log: [-4.0], [-1.0], [4.0], [2.0], [1.0], [3.0]

Once flattened, I could then run the reduce() method on the flattened array.

Here's a snippet from the code:

var my1dArray = my2dArray.flat();

var total = my1dArray.reduce((a, b) => a + b, 0);

If anyone knows a way to total the elements in a two-dimensional array without flattening it first, I would love to hear of it. Thanks for your patience.

Moggy
  • 1
  • 4