user1661677
user1661677

Reputation: 1272

Return average of all JSON values

I have a (partially) working function in which I'm attempting to find the average duration of all videos in this dataset.

It is currently only returning the the last v.duration / data.media.length, and not the sum of v.duration / data.media.length.

Any help?

$.getJSON(projectMedias, function (data) {
    $.each(data.medias, function (i, v) {
        var duration = v.duration;
        var medias = data.medias.length;
        var avg = duration/medias;
        $('#avg').html(avg); 
    })
});

Upvotes: 1

Views: 1138

Answers (3)

Juan Cortés
Juan Cortés

Reputation: 21112

The problem with your code is that you're only taking the current element of the loop into account when trying to calculate the average. For an average you need the sum of all elements and the number of elements. Inside the loop you only need to increase the total. This could be done in several ways but to keep your code mostly:

var total = 0
$.getJSON(projectMedias, function (data) {
    $.each(data.medias, function (i, v) {
        total += v.duration;
    })
    var avg = total/data.medias.length;
    $('#avg').html(avg); 
});

Bonus - Just for fun

If you want to try and do this with a one liner, you could make use of some of the newer features of javascript, and skip jQuery altogether:

var avg = data.medias.map(function(a){return a.duration;})
                     .reduce(function(a,b){return a+b;})/data.medias.length;

The first part map returns an array of, in this case, all the values of the key duration, then by calling reduce on that array we can sum all the values and end up with what on the previous code was total. Dividing that value by the total number of elements inside medias gives us the average.

Assuming a data structure similar to data = { medias : [{duration:0},{duration:10}] };

Upvotes: 2

void
void

Reputation: 36703

$.getJSON(projectMedias, function (data) {

    var _sum = 0;

    // Loop in to calculate the sum.
    [].forEach.call(data.media, function(inst){
        _sum += inst.duration;
    });

    //Devide with length to get the average
    var _avg = _sum/data.medias.length;

    $('#avg').html(_avg);
    console.log(_avg);
});

Upvotes: 0

Andrew Brooke
Andrew Brooke

Reputation: 12173

Total up the sum of the durations inside the loop, and divide by the length outside.

var sum = 0;
$.each(data.medias, function (i, v) {
    var duration = v.duration;
    sum += duration;
})
var avg = sum / data.medias.length;
$('#avg').html(avg);

Upvotes: 1

Related Questions