signal smoothing function in javascript

One way to smooth a signal in JavaScript is by applying a moving average filter. Here is an example implementation:

index.tsx
function moving_average(data, window_size) {
  var smoothed_data = [];
  var sum = 0;
  
  // Initialize average with first element
  for (var i = 0; i < window_size; i++) {
    sum += data[i];
  }
  smoothed_data.push(sum / window_size);

  // Compute moving average for remaining elements
  for (var i = window_size; i < data.length; i++) {
    sum = sum - data[i - window_size] + data[i];
    smoothed_data.push(sum / window_size);
  }

  return smoothed_data;
}
466 chars
19 lines

This function takes in an array of data and a window size (odd number representing the number of elements to average over). It then computes the moving average for each element of the array and returns a new array of the same length representing the smoothed signal.

Here's an example usage:

index.tsx
var data = [1, 2, 3, 4, 5, 4, 3, 2, 1];
var window_size = 3;
var smoothed_data = moving_average(data, window_size);
console.log(smoothed_data);
// Output: [1.67, 2.33, 3.33, 4.33, 4.33, 3.33, 2.33, 1.67]
204 chars
6 lines

This function can be modified or replaced to use other smoothing or filtering algorithms depending on the specific needs of the application.

gistlibby LogSnag