Display trend line is quite common problem while working with charts as front-end developer. Here I provide example of JS function for calculation linear trend line values and adding values to provided array of JSON values.
function(scores) {
// Calculating the Slope (m) of the Trendline
var count = scores.length;
var ySum = 0, xSum = 0, xySum = 0, xSqSum = 0;
$.each(scores, function( index, value ) {
xSum += value.day;
ySum += value.score;
xySum += value.day * value.score;
xSqSum += Math.pow(value.day, 2);
});
var slope = ((count * xySum) - (xSum * ySum)) / ((count * xSqSum) - Math.pow(ySum, 2));
// Calculating the y-intercept (b) of the Trendline
var yIntercept = (ySum - slope*xSum) / count;
$.each(scores, function( index, value ) {
value.trend = (value.day * slope) + yIntercept;
});
};