0

Is there an efficient way to calculate percent change for each key in an object?

The formula is (x/y-1)*100 - the x being arry[0].key and y is arry[1].key.

For example below is an array of objects that I would like to apply the formula above and return another object with percent changes.

var objArr = [{

        "displayAd_imp": "3500",
        "videoAd_imp": "1.5",
        "tv_imp": "0.52"
}, {
        "displayAd_imp": "1600",
        "videoAd_imp": "2.55",
        "tv_imp": "0.052"
}]

An example of the calculation would be

objArr[0].displayAd_imp / objArr[1].displayAd_imp - 1)*100 //this returns -3.74

and the data in the object would be {displayAd_imp_c : -3.74}

I'm not sure if looping both the object at the same time is a good idea, but I couldn't find a good way to loop through the keys and calculate the formula for each.

Hope I'm being clear on this, thanks for reading!

habibg
  • 185
  • 3
  • 15
  • See [How do I enumerate the properties of a javascript object?](http://stackoverflow.com/q/85992/218196) – Felix Kling Aug 22 '14 at 22:32
  • I guess this is the follow up question from your previous question here: http://stackoverflow.com/questions/25437327/calculating-change-in-percent-of-the-properties-in-javascript-objects ? – matthias_h Aug 22 '14 at 22:41
  • Yes right, I got down to two objects from calculating the week ranges and getting their sum. I just need to apply the formula now and that should give me what I need. Thanks for following the questions! – habibg Aug 24 '14 at 02:39

1 Answers1

0

something like

objArr.forEach(function(item, index) {
  if (index > 0) {
    item.displayAd_imp_c = (objArr[index-1].displayAd_imp / (item.displayAd_imp - 1) * 100;
  }
});

would probably do it in place. Not the prettiest solution, but reasonable.

pfooti
  • 2,605
  • 2
  • 24
  • 37
  • Thanks! I like the way your doing the calculation, although we just need an index for the second item - – habibg Aug 25 '14 at 14:56