function pickPeaks(arr) {
let pos = [];
let peaks = [];
for (let i = 1; i < arr.length - 1; i++) {
if (arr[i] > arr[i - 1] && arr[i] > arr[i + 1]) {
pos.push(i);
peaks.push(arr[i]);
} else if (arr[i] > arr[i - 1] && arr[i] === arr[i + 1]) {
let plateauStart = i;
while (arr[i] === arr[i + 1]) {
i++;
}
if (arr[i] > arr[i + 1]) {
pos.push(plateauStart);
peaks.push(arr[plateauStart]);
}
}
}
return { pos, peaks };
}
// Test cases
console.log(pickPeaks([
14, 0, 13, 8, 12, 13,
13, 15, -4, 10, 14, 4,
13
]));
// 13
// 15
// 14
// 6
// 3
if (arr[i] > arr[i -1] && arr[i] > arr[i + 1]){
peaks.push(arr[i]);
pos.push(i);
}
To embed this project on your website, copy the following code and paste it into your website's HTML: