zazvorniki
zazvorniki

Reputation: 3602

Averaging numbers of array columns

Ok I'm going to start with I suck at math and this is making my head spin so forgive me if I'm just being dumb. haha

I have an array or arrays that kind of looks like this, only with a ton more data in it.

[
 [3,4,6],
 [4,7,9],
 [3,8,9],
 [7,3,9]
]

And because it has so much data in it I need to average those values to put onto a graph. Some 600 plots on a graph would not be fun haha

But I don't want to average each individual array I need to average all the arrays together. Like average 3,4,3,7 and then so on. Does that make sense?

I already have a function that will average an array, but my mind can't wrap around how to do this.

average: function() {
            var cnt, tot, i;
            cnt = arguments.length;
            tot = i = 0;
            while (i < cnt) tot+= arguments[i++];
            return tot / cnt;
        },

Any help will be appreciated and will stop me from throwing the computer out the window. :)

Upvotes: 0

Views: 48

Answers (2)

rfportilla
rfportilla

Reputation: 308

The arrays are just in the wrong format. But that is ok. This can be fixed with a loop. This code loops through them and stores the sum, count, and average for each as it goes through them.

    <html>
<head>
<script>
// sample data
var samarr = [[1,2,3],[3,7,9],[2,8,4],[6,2,2],[9,1,5]];
// new array that holds total for each column (0,1,2); in each I am storing 3 values (sum,count, avg).
var newarray = [[0,0,0],[0,0,0],[0,0,0]];


//for each array in sample data...
for(i = 0; i < samarr.length; i++){
    //for each element in the array
    for(j=0; j<samarr[i].length; j++){
        //put the data in the new array
        //this keeps a rolling value of the sum
        newarray[j][0] += samarr[i][j];
        //this keeps a rolling value of the number of elements
        newarray[j][1]++;
        //this keeps a rolling value of the average
        newarray[j][2] = newarray[j][0]/newarray[j][1];
    }
}

//This dumps the new array to an alert box. ;-)
alert(newarray);
</script
</head>
<body>


</body>
</html>

Upvotes: 0

AmmarCSE
AmmarCSE

Reputation: 30607

var twoDimArr = [
  [3, 4, 6],
  [4, 7, 9],
  [3, 8, 9],
  [7, 3, 9]
];
for (var i = 0; i < twoDimArr[0].length; i++) {
  var sum = 0;
  for (var j = 0; j < twoDimArr.length; j++) {
    sum += twoDimArr[j][i];
  }
  var avg = sum / twoDimArr.length;
  console.log(avg);
}

Upvotes: 3

Related Questions