I have a JavaScript object :
var avgHeight = AvgHeight({height:174, weight:69}, {height:190, weight:103}, {height:500, weight:103});
I want to add all the height values and return the average.
For example: 174+190+500/3 = xxx
How do I iterate and fetch the property values from the above object.
3 Answers 3
You need to append each value to total using reduce and return sum, and after getting sum we will get the average. below is my code
function getAverage(data){
const totalBob = data.reduce((total, purchase) => {
total += purchase.height;
return total;
}, 0)/data.length;
//var ave = totalBob / data.length;
return totalBob;
}
const data = [
{ height: 174, weight: 69 },
{ height: 190, weight: 103 },
{ height: 500, weight: 103 }
];
var res = getAverage(data);
console.log(res);
answered Nov 30, 2017 at 13:41
Comments
Use reduce
function AvgHeight(arr)
{
return arr.reduce( (a,b) => a += b.height, 0 )/arr.length;
}
Demo
function AvgHeight(arr) {
return arr.reduce((a, b) => a += b.height, 0) / arr.length;
}
console.log(AvgHeight([{
height: 174,
weight: 69
}, {
height: 190,
weight: 103
}, {
height: 500,
weight: 103
}]));
answered Nov 30, 2017 at 13:33
Comments
Less elegant than @gurvinder372 solution, but it could give you some tips about arrays / objects fetching :
function computeAvg(arr) {
var result = 0;
for (var key in arr) {
result += arr[key].height;
}
return result / arr.length;
}
var avgHeight = [
{ height: 174, weight: 69 },
{ height: 190, weight: 103 },
{ height: 500, weight: 103 }
];
var avg = computeAvg(avgHeight);
console.log(avg);
answered Nov 30, 2017 at 13:43
Comments
lang-js
AvgHeight
function