adapap
adapap

Reputation: 665

JavaScript: Trouble with reduce

I'm attempting to obtain a sum of one array in a larger group. The code updates the first array value in the first array, but the reduce function is not working. Here is the code:

JavaScript (HTML to see result):

var boughtRaw = [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0]];

var boughtCalc = function (level) {
    boughtRaw[0[0]] = 5
    var Raw = boughtRaw[level];
    window["boughtList" + level] = Raw.reduce(function(a, b) {
    return a + b;}, 0);
  };
 
boughtCalc(0);  
document.getElementById("debug").innerHTML = boughtList0;
  /* Should return 5 */
<span id="debug" style="border: 1px dashed red">Debug</span>

Upvotes: 2

Views: 53

Answers (1)

adricadar
adricadar

Reputation: 10219

You have to correct boughtRaw[0[0]] = 5 into this line boughtRaw[0][0] = 5.

var boughtRaw = [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0]];

var boughtCalc = function (level) {
    boughtRaw[0][0] = 5; // corrected
    var Raw = boughtRaw[level];
    window["boughtList" + level] = Raw.reduce(function(a, b) {
    return a + b;}, 0);
  };
 
boughtCalc(0);  
document.getElementById("debug").innerHTML = boughtList0;
/* return 5 */
<span id="debug" style="border: 1px dashed red">Debug</span>


To access elements of an array(of array .. of array) you have to place []...[] next to each other, not like this [[...[]]].

var element1 = array[0] // get first element of array
var element2 = element1[0] // get first element of element1 
.....
var result = elementN[0] // get first element of elementN

This can be replaced with

var result = array[0][0]...[0].

Upvotes: 3

Related Questions