lowpass filter in javascript

Here's an example implementation of a basic lowpass filter in JavaScript:

index.tsx
function lowpassFilter(signal, cutoffFreq, sampleRate) {
  // Calculate the filter coefficients
  var RC = 1.0 / (cutoffFreq * 2 * Math.PI);
  var dt = 1.0 / sampleRate;
  var alpha = dt / (RC + dt);
  
  // Apply the filter to the input signal
  var filteredSignal = [];
  var prevFilteredSample = 0;
  for (var i = 0; i < signal.length; i++) {
    var filteredSample = alpha * signal[i] + (1 - alpha) * prevFilteredSample;
    filteredSignal.push(filteredSample);
    prevFilteredSample = filteredSample;
  }
  
  return filteredSignal;
}
541 chars
18 lines

The function takes three arguments: the input signal, the cutoff frequency of the lowpass filter (in Hz), and the sample rate of the input signal (in samples per second). It returns the filtered signal as an array of samples.

The filter works by recursively applying a weighted average of each input sample and the previous filtered sample, with a weight determined by the cutoff frequency and sample rate. This attenuates high-frequency components of the signal and passes through lower-frequency components.

gistlibby LogSnag