# Can only one loop be used to calculate percentage?

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.comNov 21 '13 at 15:10

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

• Since you need totalValue to compute the label, it seems like it might be hard to stick one loops. – mr rogers Nov 21 '13 at 6:48
• I don't think it is possible.. because first you need to find the total then the percentage – Arun P Johny Nov 21 '13 at 6:48
• 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%, ... – Bikas Nov 21 '13 at 6:49
• @Bart care to explain more? – Bikas Nov 21 '13 at 6:52
• create a jsfiddle for that.. – 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.