4

So basically i have a 1d array with over 500 values floating between the ranges of 100- 130 or about there arranged in no particular order(its random); and I wanna know how can I find the peaks and troughs of this data. Is there a way to also change sensitivity of the peak detection? What is a comprehensive algorithm for this? If there is a JS library for it, that would be awesome.

1 Answers1

1

An algorithm for finding peaks and troughs would be essentially the same thing you would do with your finger when looking at a graph. You go from the start and follow the line and take note when you see a peak and a trough.

Programmically we can define that as this:

For some array of length n (with n-1 being the index of the last element and 0 the index of the first), iterate thorough from 1 to n-2. Then peaks and troughs would be defined as:

  • For element i, if i-1 > i and i+1 > i. Then i is a trough.
  • For element i, if i-1 < i and i+1 < i. Then i is a peak.

This would be an O(n) algorithm and be enough information to be able to program it.


Below is an example program implementing the algothim above:

var array = [102,112,115,120,119,102,101,100,103,105,110,109,105,100];

function findPeaksAndTroughs(array) {
  var start = 1;                        // Starting index to search
  var end = array.length - 2;           // Last index to search
  var obj = { peaks: [], troughs: []  };// Object to store the indexs of peaks/thoughs
  
  for(var i = start; i<=end; i++)
  {
    var current = array[i];
    var last = array[i-1];
    var next = array[i+1];
    
    if(current > next && current > last) 
     obj.peaks.push(i);
    else if(current < next && current < last) 
     obj.troughs.push(i);
  }
  return obj;
}

console.log(findPeaksAndTroughs(array));
Spencer Wieczorek
  • 21,229
  • 7
  • 44
  • 54