Skip to content
Sign upLog in
← Back to Community
100_getAverageOfElementsAtProperty
Profile icon
soniass1

/*
Write a function called "getAverageOfElementsAtProperty".

Given an object and a key, "getAverageOfElementsAtProperty" returns the average of all the elements in the array located at the given key.

Notes:
* If the array at the given key is empty, it should return 0.
* If the property at the given key is not an array, it should return 0.
* If there is no property at the given key, it should return 0.

var obj = {
key: [1, 2, 3]
};
var output = getAverageOfElementsAtProperty(obj, 'key');
console.log(output); // --> 2
*/

function getAverageOfElementsAtProperty(obj, key) {
var count = 0;
var average = 0;
if(obj[key]<1 || !Array.isArray(obj[key])){return 0;}
for(var prop in obj[key]){
count = count + obj[key][prop];
}
average = count/obj[key].length
return average;

}

Voters
Profile icon
AlmazBakirov1
Profile icon
soniass1