Search code examples
arrayslisterror-handlingoutliers

How to remove the error values by replacing them?


I have an array with values collected from a sensor. However, once in a while, the sensor returns an error value. I want to replace these values by interpolating them using the closest values in the array. How can I do that easily, considering I can have several error values consecutively?

sensor = [20, 21, 22, 21, 8190, 20, 19, 20, 21, 22, 23, 24, 8190, 8190, 25, 21, 8190]

I want to have this:

sensor = [20, 21, 22, 21, 20.5, 20, 19, 20, 21, 22, 23, 24, 24.5, 24.5, 25, 21, 21]

Solution

  • You can just do something like

    const sensor = [20, 21, 22, 21, 8190, 20, 19, 20, 21, 22, 23, 24, 8190, 8190, 25, 21, 8190]
    

    //create a new array and variable

    let  arr=[]
    let currentNum
    

    //iterate over the old array

    sensor.forEach(element =>{ 
      if(element!==8190){
         arr.push(element)
         currentNum=element
      }else{
        currentNum=currentNum+.5
    
         arr.push(currentNum)
      }
    });
    
    
    
    console.log(arr)