HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Can only one loop be used to calculate percentage?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
canusedlooponecalculateonlypercentage

Problem

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.

Solution

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.

Context

StackExchange Code Review Q#35842, answer score: 5

Revisions (0)

No revisions yet.