JavaScript: fitting a line with least squares

Simple linear regression finds the line y = m·x + b that minimizes the sum of squared vertical errors. For one input variable there is a closed-form solution: the slope is the covariance of x and y divided by the variance of x, and the intercept makes the line pass through the point of means.

JavaScript
const x = [1, 2, 3, 4, 5];
const y = [2.2, 4.1, 6.2, 7.9, 10.1];

const mean = (values) => values.reduce((a, b) => a + b, 0) / values.length;
const mx = mean(x);
const my = mean(y);

let sxy = 0;
let sxx = 0;
for (let i = 0; i < x.length; i++) {
  sxy += (x[i] - mx) * (y[i] - my);
  sxx += (x[i] - mx) ** 2;
}
const slope = sxy / sxx;
const intercept = my - slope * mx;

let residual = 0;
let total = 0;
for (let i = 0; i < x.length; i++) {
  residual += (y[i] - (slope * x[i] + intercept)) ** 2;
  total += (y[i] - my) ** 2;
}

console.log("slope " + slope.toFixed(3) + ", intercept " + intercept.toFixed(3));
console.log("R squared " + (1 - residual / total).toFixed(4));
console.log("prediction for x=6: " + (slope * 6 + intercept).toFixed(2));
Read the full lesson