Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

sum 2d array javascript

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));
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #sum #array #javascript
ADD COMMENT
Topic
Name
3+1 =