0

how can I able to find the average of the polarity data from the JSON file? I just can't seem to access it. I need the average as a var so I can use this input to my chart, using "chart.js" API.

Here is my code below:

        var sum = 0;
        var avg = 0;
        var xmlhttp = new XMLHttpRequest();
        var url = "moderna_updated.json";
        xmlhttp.open("GET",url,true);
        xmlhttp.send();
        xmlhttp.onreadystatechange = function(){
            if(this.readyState == 4 && this.status == 200){
                var data = JSON.parse(this.responseText);
                var polarities = data.tweets.map(function(elem){
                    return elem.polarity;
                });
                //console.log(polarities);
            } 
        }

Here is a sample of my JSON file below:

{
"tweets": [
    {
        "tweetcreatedts": "2021-03-10 23:59:51",
        "polarity": 0.0,
        "score": "neutral"
    },
    {
        "tweetcreatedts": "2021-03-10 23:59:51",
        "polarity": 0.15,
        "score": "positive"
    },
    {
        "tweetcreatedts": "2021-03-10 23:59:36",
        "polarity": 0.0,
        "score": "neutral"
    },
    {
        "tweetcreatedts": "2021-03-10 23:59:36",
        "polarity": 0.4,
        "score": "positive"
  ]}
  • I don't see any attempt at calculating an average.... What is the issue in doing that? *"I just can't seem to access it."*: what exactly does that mean? You get an error? You get an undefined value? – trincot Mar 19 '21 at 21:37
  • Does this answer your question? [How to compute the sum and average of elements in an array?](https://stackoverflow.com/questions/10359907/how-to-compute-the-sum-and-average-of-elements-in-an-array) – Lil Devil Mar 19 '21 at 21:40
  • i just cant seemed to access the values when i tried to for a for loop right after //console.log(polarities); for(i=0; i < polarities.length; i++){ sum += polarities } avg = sum/polarities.length – Redoxsphere Mar 19 '21 at 21:40

1 Answers1

1

Well.. calculating the averaging sound like a job for.... summing the elements and dividing the result by the number of elements.

var avg_polarity = polarities.reduce((sum, polarity) => (sum + polarity)) / polarities.length
lwohlhart
  • 1,829
  • 12
  • 20