In this question I encountered the following simplified problem:
We start with an array of Objects with a value attribute. We want to calculate for each value what percentage of the sum of values it is, and add it to the structure as a property. To do this, we need to know the sum of values, but this sum is not calculated beforehand.
//Original data structure
[
{ "value" : 123456 },
{ "value" : 12146 }
]
//Becomes
[
{
"value" : 123456,
"perc" : 0.9104
},
{
"value" : 12146 ,
"perc" : 0.0896
}
]
An easy, and probably most readable, solution is to go through the data structure twice. First we calculate the sum, then we calculate the percentage and add it to the data structure.
var i;
var sum = 0;
for( i = 0; i < data.length; i++ ) {
sum += data[i].value;
}
for( i = 0; i < data.length; i++ ) {
data[i].perc = data[i].value / sum;
}
Can we instead just go through the data structure once, and somehow tell that the percentage expression should only be evaluated once the entire sum is known?
I am primarily interested in answers that address pure javascript. That is: Without any libraries.
n
values and writen
values. I am just curious if there is a certain syntax or construct that allows me to defer assignment of the percentage until the sum is known by, possibly, putting something in the first loop. – Tortilla