My dataset contains an array with thousands of objects structured like this:
var data = [
{type:'A',time:'2009'},
{type:'A',time:'2009'},
{type:'A',time:'2009'},
{type:'A',time:'2009'},
{type:'B',time:'2009'},
{type:'B',time:'2009'},
{type:'B',time:'2009'},
{type:'C',time:'2009'},
{type:'A',time:'2014'},
{type:'A',time:'2014'},
{type:'B',time:'2014'},
{type:'B',time:'2014'},
{type:'B',time:'2014'},
{type:'B',time:'2014'},
{type:'C',time:'2014'},
{type:'C',time:'2014'}
];
var validTime = ['2009', '2014'];
var typeArr = ['A','B','C'];
To simplify and consolidate the data, I aim to transform the 'data
' array into a new structure called 'newData
'. This new structure should calculate the count of each type for every year.
var newData = [
{time:'2009', A:4, B:3, C:1},
{time:'2014', A:2, B:3, C:2}
]
I have made some progress in my implementation, but feel that I might not be following the best approach. Being relatively new to JavaScript, I'm seeking guidance on how to proceed or any useful web resources that tackle similar problems. Any assistance would be greatly appreciated! Thanks!
If possible, please include comments in your response.
var arr1 = [];
for (i = 0; i < validTime.length; i++) {
for (s = 0; s < typeArr.length; s++) {
var count = 0;
for (j = 0; j < data.length; j++) {
if (data[j]['time'] == validTime[i] && data[j]['type'] == typeArr[s]){
count++;
}
}
arr1.push({
'type': typeArr[s],
'x': validTime[i],
'y': count
});
}
};
console.log(arr1);