-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>
8
  • 1
    data[i] is an object, so a classic for-loop over it won't work. Commented Aug 23, 2013 at 12:26
  • possible duplicate of Iterating over objects in Javascript Commented Aug 23, 2013 at 12:28
  • Just change your for loop. Commented Aug 23, 2013 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. Commented Aug 23, 2013 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. Commented Aug 23, 2013 at 13:29

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

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!!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.