1

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.

Roars
6545 silver badges17 bronze badges
asked Nov 30, 2017 at 13:30
1
  • Share the code of AvgHeight function Commented Nov 30, 2017 at 13:32

3 Answers 3

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

2

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

1

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);

https://jsfiddle.net/1gkjLb2c/

answered Nov 30, 2017 at 13:43

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.