JSFiddle - React, Tailwind, and code Playground
by epoch
JavaScript
var scores = [{
category: "assignment",
date: '2/13/13',
earned: 9,
total: 10
}, {
category: "assignment",
date: '2/13/13',
earned: 8.5,
total: 10
}, {
category: "test/quiz",
date: '2/7/13',
earned: 85,
total: 100
}];
var weights = {
"assignment": 40,
"test/quiz": 60
};
function calculateCombined() {
var dates = [], combined = [];
for (var i = 0; i < scores.length; i++) {
if (!dates[scores[i].date]) {
dates[scores[i].date] = [];
}
dates[scores[i].date].push({
weight: weights[scores[i].category] || 1,
percentage: (scores[i].earned / scores[i].total) * 100
});
}
for (var x in dates) {
if (dates.hasOwnProperty(x)) {
var tWeight = 0;
dates[x].forEach(function(dVal) {
tWeight += (dVal.weight / 100) * dVal.percentage
});
combined.push({
date: x,
wight: tWeight
});
}
}
return combined.sort(function(d, e) {
return new Date(d.date) - new Date(e.date);
});
}
console.log(calculateCombined());