admin管理员组

文章数量:1410737

I am receiving real-time responses from the back-end that contains the following JSON (almost every second):

One Array:

 {
"newUpdate": [ 
{
    "id": "TP", 
    "val" : 3
},
{ 
    "id": "TPE20", 
    "val" : 3
}]
 }

Another array (after one second or less)

 {
"newUpdate": [ 
{
    "id": "CRK", 
    "val" : 24
},
{ 
    "id": "TPE20", 
    "val" : 44
}]
 }

I am getting the above JSON almost every second knowing that each time it es with different values and id's, and the array itself does not have a specific size.

Well, what I want to do is to get the average of the values having the same key 'id'.

For example, for the above array, the average will be for TPE20 :

(3+44)/2 =23.2 (as it putes the average for the id : TPE20)

Then it should show it here (using JQuery for example) [Think of the real-time average value like in the stock market]

<div id="TPE20"></div>

Currently, using the below for loop, I print the JSON listed above:

for(var i in load.updates){
var id =     load.newUpdate[i].id;
updatesMap[id] = load.newUpdate[i].value;
var valueOfID = newUpdate[id];
}

The challenge is that I am receiving a lot of arrays at once (1/sec), each array contains different "id" and "val", I really don't know how I can pute the average using the way I described above!

I am receiving real-time responses from the back-end that contains the following JSON (almost every second):

One Array:

 {
"newUpdate": [ 
{
    "id": "TP", 
    "val" : 3
},
{ 
    "id": "TPE20", 
    "val" : 3
}]
 }

Another array (after one second or less)

 {
"newUpdate": [ 
{
    "id": "CRK", 
    "val" : 24
},
{ 
    "id": "TPE20", 
    "val" : 44
}]
 }

I am getting the above JSON almost every second knowing that each time it es with different values and id's, and the array itself does not have a specific size.

Well, what I want to do is to get the average of the values having the same key 'id'.

For example, for the above array, the average will be for TPE20 :

(3+44)/2 =23.2 (as it putes the average for the id : TPE20)

Then it should show it here (using JQuery for example) [Think of the real-time average value like in the stock market]

<div id="TPE20"></div>

Currently, using the below for loop, I print the JSON listed above:

for(var i in load.updates){
var id =     load.newUpdate[i].id;
updatesMap[id] = load.newUpdate[i].value;
var valueOfID = newUpdate[id];
}

The challenge is that I am receiving a lot of arrays at once (1/sec), each array contains different "id" and "val", I really don't know how I can pute the average using the way I described above!

Share asked Mar 22, 2016 at 23:50 Hamza L.Hamza L. 1,8234 gold badges28 silver badges47 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

Just use an object with keys representing the ids of the array objects and the values as objects containing the count, total, and average of those ids.

When you receive a new array simply update the object:

function updateObj(arr) {
  arr.forEach(function(el) {
    var key = el.id;
    obj[key] = obj[key] || { count: 0, total: 0, avg: 0 };
    obj[key].count++;
    obj[key].total += el.val;
    obj[key].avg = obj[key].total / obj[key].count;
  });
}

Here's a simulation with setInterval sending one array to the function each second, and then displaying the pleted object in the console.

Does this help? It get the Average of the search term like you asked. It uses jquery $.each to iterate through the array

var newdata = [
  {
    "newUpdate": [ 
      {
        "id": "TP", 
        "val" : 3
      },
      { 
        "id": "TPE20", 
        "val" : 3
      }]
  },
  {
    "newUpdate": [ 
      {
        "id": "CRK", 
        "val" : 24
      },
      { 
        "id": "TPE20", 
        "val" : 44
      }]
  }
]

function getAverage(array, term){
  var sum = 0, n = 0;
  $.each(array, function(i, item){
    n++
    var arrs = item.newUpdate
    $.each(arrs, function(d, place){
      // console.log(d)
      if (place.id == term){
        sum +=place.val 
      }


    })

  })
  return sum / n
}

document.write(getAverage(newdata, "TPE20"))
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.0/jquery.min.js"></script>

You can use Array.prototype.forEach() , create a private property at an object to store number of occasions unique property occurs within callback; pass each object individually to function in succession to maintain averages of properties at single object

var a = {
  "newUpdate": [{
    "id": "TP",
    "val": 3
  }, {
    "id": "TPE20",
    "val": 3
  }]
};

var b = {
  "newUpdate": [{
    "id": "CRK",
    "val": 24
  }, {
    "id": "TPE20",
    "val": 44
  }]
}

var avg = {};

function update(update) {

  update.newUpdate.forEach(function(value, index) {
    if (!avg[value.id] || !avg.hasOwnProperty(value.id)) {
      avg["_" + value.id] = 1;
      avg[value.id] = value.val / avg["_" + value.id];
    } else {
      ++avg["_" + value.id];
      avg[value.id] += value.val;
      avg[value.id] = avg[value.id] / avg["_" + value.id];
    }

  });
  
  return avg
  
}

console.log(update(a), update(b), avg)

本文标签: jqueryJavaScriptJSONGet the total average of values having the same key from multiple arraysStack Overflow