-1

I wanted to calculate the average of the innermost arrays as mentioned below without using names of the properties. Is there a way out. I am using javascript. Currently using this syntax, i am getting the array is not defined.

average.js

var data=
[
{
 "load":[1,2,3],
"network":[5,6,7]
},
{
"load":[10,11,12],
 "network":[14,15,16]
  }
 ]
  // I want to calculate the average for each of the properties 'load','network' and many more....
 function avg(i)
 {
 for(j=0;j<data[i].length;j++)
 {
 sum=0;
 for(k=0;j<data[i][j].length;k++)
 {
 sum+=data[i][j][k];// it do not seems correct
 }
 average=sum/3;
 document.write("value "+i+":"+average);//just for testing
 }
 }

average.html

 <!DOCTYPE html>
 <meta charset="utf-8">
 <head>
 <script src="average.js"></script>
  </head>
 <body>
 <script>
 avg();
  </script>
 </body>
  </html>
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
Varun Singh
  • 310
  • 2
  • 10
  • 1
    `data[i]` is an object, so a classic for-loop over it won't work. – John Dvorak Aug 23 '13 at 12:26
  • possible duplicate of [Iterating over objects in Javascript](http://stackoverflow.com/questions/8389148/iterating-over-objects-in-javascript) – John Dvorak Aug 23 '13 at 12:28
  • Just change your for loop. – Jay Shukla Aug 23 '13 at 12:41
  • @varunsingh access arrays as arrays and objects as objects. If you have an array of objects, write an array-loop with an object-loop inside. If you can do either, you should be able to do both. – John Dvorak Aug 23 '13 at 13:17
  • @JanDvorak: Thanks 4 ur reply.The link u mentioned uses the d3.keys to extract the values. And I don't want to use d3.js .Also, in my case there is array of values in **load etc**. I want to access that. Can i do? If yes, show me the way. – Varun Singh Aug 23 '13 at 13:29
  • The accepted answer mentions nothing about D3. Just use `for..in` like the answer shows, and classic `for` for arrays like you already know. – John Dvorak Aug 23 '13 at 13:31
  • also, no need to use text speak. There is plenty of space here. Textspeak is only going to aggravate people. Please cease immediately. – John Dvorak Aug 23 '13 at 13:32
  • @jan Dvorak: okk fine. I am new to javascript, that's why i couldn't understand ur answer. The answer below explained me much better. – Varun Singh Aug 23 '13 at 18:18

1 Answers1

0

Try this

function avg(i)
{
    for(j in data[i])
    {
        sum=0;
        for(k=0;k<data[i][j].length;k++)
        {
            sum+=data[i][j][k];
        }
        average=sum/3;
        document.write("value "+i+":"+average);
    }
}

Call it like this

<script>
   avg(0); // Index 
</script>

Working Fiddle DEMO

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
Jay Shukla
  • 5,794
  • 8
  • 33
  • 63
  • This also doesn't work. It is giving the result like **value 0:0 and only two times**. God knows, where the third iteration went!!! – Varun Singh Aug 23 '13 at 13:20