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.
Asked
Active
Viewed 3,690 times
4
-
It would help if we could a) see your data and b) see what you've tried thus far. – gyre Apr 23 '17 at 04:22
-
so its literally one array like var thisthing = [102.54,112.23, etc... for 500 values. I didn't try anything cuz i dont know how to proceed. – Lifeislifebutwhatiswhat Apr 23 '17 at 04:43
1 Answers
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
, ifi-1 > i
andi+1 > i
. Theni
is a trough. - For element
i
, ifi-1 < i
andi+1 < i
. Theni
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