This is my data:
const data = [{
"cluster": 1,
"year": 2010
},
{
"cluster": 1,
"year": 2020
},
{
"cluster": 1,
"year": 2020
},
{
"cluster": 2,
"year": 2010
},
{
"cluster": 3,
"year": 2015
}
];
I would like to have this as my result:
accumulatedData = [{
"cluster": 1,
years: [{
year: 2010,
frequency: 1
},
{
year: 2020,
frequency: 2
}
]
},
{
"cluster": 2,
years: [{
year: 2010,
frequency: 1
},
{
year: 2015,
frequency: 0
}
]
},
{
"cluster": 3,
years: [{
year: 2015,
frequency: 1
}, {
year: 2020,
frequency: 0
}]
}
];
console.log(accumulatedData);
In words, I would like to:
- structure the
datainto the 3clusters. - add objects for each
yearwithin a specificcluster - add the
frequencyof the occurence of ayearin a specificcluster
I’ve realised that the reduce function might be useful here. I’ve managed to set the structure, but I am stuck in adding the values in the objects. Especially accumulating the number of times a year occurs in a particular cluster.
Am I on the right track, or would a for loop be better?
const data = [{
"cluster": 1,
"year": 2010
},
{
"cluster": 1,
"year": 2020
},
{
"cluster": 1,
"year": 2020
},
{
"cluster": 2,
"year": 2010
},
{
"cluster": 3,
"year": 2015
}
];
var accumulatedData = {};
accumulatedData = data.reduce((a, b) => {
a[b.cluster] = [{
"year": 0,
"frequency": 0
}];
a[b.cluster].year = b.year;
a[b.cluster].frequency = a[b.cluster].frequency + 1;
return a;
}, {})
console.log("accumulatedData", accumulatedData);




