I have an array like this:
var data =
[
{label:1, quater :'Q1', y:34},
{label:2, quater:'Q1', y:20},
{label:3, quater:'Q1', y:30},
{label:1, quater:'Q2', y:77},
{label:2, quater:'Q2', y:52},
{label:3, quater:'Q2', y:3},
{label:1, quater:'Q3', y:65},
{label:2, quater:'Q3', y:12},
{label:3, quater:'Q3', y:9},
{label:1, quater:'Q4', y:77},
{label:2, quater:'Q4', y:34},
{label:3, quater:'Q4', y:5}
];
My goal is to add "percent" into each object. Each "percent" is the percentage of the value of y in current object devided by the sum of values of y in quater from Q1 to Q4. For example, the percent in first boject should be 34/(34+77+65+77) The code below is what I tried. It works and calculats the data correctly. I am new to javascript, so I calculate the data step by step which makes the code look long.
I am wondering what is the smarter way to calculate the data to make the code shorter? Thanks!
var quater = ["Q1","Q2","Q3","Q4"];
var sum = 0;
var arr = [];
for(var i = 0; i<quater.length; i++){
for(var j = 0; j<data.length; j++){
if (data[j]['quater'] == quater[i])
sum = sum + data[j]['y'];
}
//console.log(sum)
arr.push({
'quater': quater[i],
'sum': sum
})
sum = 0;
}
var arr1 = [];
var percent;
for(var i = 0; i<data.length;i++){
for(var j = 0; j<arr.length; j++){
if(data[i]['quater'] == arr[j]['quater']){
percent = data[i]['y']/arr[j]['sum'];
}
}
//console.log(percent)
arr1.push({
'label': data[i]['label'],
'y': data[i]['y'],
'quater': data[i]['quater'],
'percent': percent
});
}
console.log(arr1)