Kontakt
Kontakt

Reputation: 111

Javascript for loop nested iteration

I'm trying to iterate through a large array of values and collect an average of one of the values for each second. I can't get this code to work properly, and as far as I can see the issue is with the nested while loop. am I making a scope error that's preventing me from iterating the for loop index?

The data is a timestamp in ms and a radiation count. a.data[i][0] is the timestamp and a.data[i][26] is the count.

for (i = 0; i < a.data.length; i++){
    // counts is the count of radiation over the last timeframe
    var counts = 0;
    // t1 is the start time 
    // t2 is the current iteration time
    var t1, t2 = a.data[i][0];
    while ((t2 - t1) < 1000){
        t2 = a.data[i][0];
        counts += a.data[i][26];
        i++;
    }
    // Geiger Data is an array of { x:(time), y:(value)} datapoints.
    GeigerData.push({x: (t1/1000), y: counts});
}

Upvotes: 1

Views: 61

Answers (1)

nmarsh
nmarsh

Reputation: 164

You problem stems from this line:

 var t1, t2 = a.data[i][0];

Defining JS variables doesn't work like that, and in your code t1 is always undefined. What you really want is

 var t1 = a.data[i][0];
 var t2 = t1;

Upvotes: 2

Related Questions