I've a requirement to find sum of an attribute of each JSON row and then add another attribute to show percentage of corresponding attribute. The JSON is as follows -

    {"value":150, ...},
    {"value":125, ...},
    {"value":100, ...},
    {"value":60, ...},
    {"value":30, ...}

Now, I've written following code.

var totalVal = 0;
$.each(data, function(index, value) {
    totalVal += value.value;
$.each(data, function(index, value) {
    value.label = Math.round((value.value / totalVal) * 10000) / 100 + "%";

I've to use 2 loops to achieve the result. Is there any way to do this in single loop?

EDIT: The code I've written works perfectly. Since I'm contributing back to publicly available GitHub project, I really want to know if the method is most efficient.


migrated from stackoverflow.com Nov 21 '13 at 15:10

This question came from our site for professional and enthusiast programmers.

  • \$\begingroup\$ Since you need totalValue to compute the label, it seems like it might be hard to stick one loops. \$\endgroup\$ – mr rogers Nov 21 '13 at 6:48
  • 2
    \$\begingroup\$ I don't think it is possible.. because first you need to find the total then the percentage \$\endgroup\$ – Arun P Johny Nov 21 '13 at 6:48
  • \$\begingroup\$ No. The result will be all wrong. See in loop execution totalValue will vary as 150, 275, ... So your percentage vary as 100%, 45.45%, ... \$\endgroup\$ – Bikas Nov 21 '13 at 6:49
  • \$\begingroup\$ @Bart care to explain more? \$\endgroup\$ – Bikas Nov 21 '13 at 6:52
  • \$\begingroup\$ create a jsfiddle for that.. \$\endgroup\$ – Javascript Coder Nov 21 '13 at 6:53

No, totatVal won't be a totalVal until you loop through all the rows to find it. It might be solved by a single loop with some fancy standard functions but at the end it will come down to 2 loops.

It's pure math - you need to count your total value first in order to find a correct % of each of your values.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.