0

how do I access the integers in the data object of this array?

Ultimately, I want to write a for loop to enter and compute the vpos (vertices).

var arrays = {
vpos : { numComponents: 3, data: 
                [
                    -.5,-1,-.5,  .5,-.5,-.5,  .5, .5,-.5,
                    -.5,-.5,-.5,  .5, .5,-.5, -.5, .5,-.5,
                    -.5,-.5, .5,  .5,-.5, .5,  .5, .5, .5
                ] },
    vnormal : {numComponents:3, data: [
                    0,0,-1, 0,0,-1, 0,0,-1,
                    0,0,-1, 0,0,-1, 0,0,-1,
                    0,0,1, 0,0,1, 0,0,1,
                    ]}
            };
PM 77-1
  • 12,933
  • 21
  • 68
  • 111
Raoul Duke
  • 127
  • 7

4 Answers4

1

You can easily calculate the total with reduce:

let total = arrays.vpos.data.reduce((sum, val) => sum + val, 0);

Here is a demonstration:

var arrays = {
  vpos: {
    numComponents: 3,
    data: [-.5, -1, -.5, .5, -.5, -.5, .5, .5, -.5, -.5, -.5, -.5, .5, .5, -.5, -.5, .5, -.5, -.5, -.5, .5, .5, -.5, .5, .5, .5, .5]
  }
};

let total = arrays.vpos.data.reduce((sum, val) => sum + val, 0);
console.log(total);
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338
0

Just use [index] notation. Index is zero-based (first item has index of 0, 2nd one - 1, and so on).

arrays.vpos.data[0] //gives -0.5
arrays.vpos.data[1] //gives -1
arrays.vpos.data[2] //gives -0.5
entio
  • 3,816
  • 1
  • 24
  • 39
0

For vpos:

var pushedArray;
for(var x of arrays.vpos.data) {
    pushedArray.push(x);
}

pushedArray will have the values from the data array in it.

To add them:

var sum;
for(var x of pushedArray) {
    sum += x;
}
ewizard
  • 2,801
  • 4
  • 52
  • 110
-1

Yes you can get data array in d and then create for loop

var v =  {
vpos : { numComponents: 3, data: 
                [
                    -.5,-1,-.5,  .5,-.5,-.5,  .5, .5,-.5,
                    -.5,-.5,-.5,  .5, .5,-.5, -.5, .5,-.5,
                    -.5,-.5, .5,  .5,-.5, .5,  .5, .5, .5
                ] },
    vnormal : {numComponents:3, data: [
                    0,0,-1, 0,0,-1, 0,0,-1,
                    0,0,-1, 0,0,-1, 0,0,-1,
                    0,0,1, 0,0,1, 0,0,1,
                    ]}
            };
            var d = v.vpos.data;
            console.log(d);
Justin
  • 137
  • 1
  • 5