Get average of each nested array in dynamic object I'm iterating this JSON using a for loop:

var movieObj = {
    "cat": {
        "moveName": "Breath",
        "rating": [4, 5, 4, 3]
    },
    "cat1": {
        "moveName": "shallow",
        "rating": [5, 5, 5, 5, 4]
    }
}


Is there any way to improve this code?

var sum;

Array.prototype.getSum = function (ele) {
    sum = ele.reduce(function (a, b) {
        return a + b
    });
    return sum / ele.length
}

for (var key in movieObj) {
    var b = movieObj[key];

    if (Array.prototype.getSum(b['rating']) &lt; 5) {
        console.log(b['moveName']);
    }
}
First off, you should ensure that each key is a properly defined member of movieObj, not part of the prototype:

for (var key in movieObj) {
    if (movieObj.hasOwnProperty(key)) {
        // ...
    }
}


Instead of declaring getSum on Array, you can use the builtin reduce function:

var sum = function(previous, current) {
    return previous + current;
};

var ratings = movieObj[key].rating;

if (ratings.reduce(sum) / ratings.length &lt; 5) {
    // ...
}


Finally, your console.log statement can use direct property access, instead of square bracket notation.  I believe moveName is a typo, and should in fact be movieName, but correct me if I'm wrong there:

console.log(movieObj[key].movieName);


Putting it all together gives:

var sum = function(previous, current) {
    return previous + current;
};

for (var key in movieObj) {
    if (movieObj.hasOwnProperty(key)) {
        var ratings = movieObj[key].rating;

        if (ratings.reduce(sum) / ratings.length &lt; 5) {
            console.log(movieObj[key].movieName);
        }
    }
}