I have an ultrasonic sensor measuring distance in air. I get spurious readings periodically.
Rather than try to average them out I:
- Read 9 readings into an array
- sorted the array
- used the middle reading.
You could take more readings and use the middle 3 averaged.