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.

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

Sign up to request clarification or add additional context in comments.

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

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/

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.