Skip to content

Instantly share code, notes, and snippets.

@redrambles
Created November 8, 2021 19:40
Show Gist options
  • Save redrambles/4eaaed2b90c9d1ecff49dd7e5d9ad383 to your computer and use it in GitHub Desktop.
Save redrambles/4eaaed2b90c9d1ecff49dd7e5d9ad383 to your computer and use it in GitHub Desktop.
Cassidoo Challenge - Find Local Peaks
/**
* Returns array of indices of local peaks in given array
*
* @param {array of integers} arr - The array where we will discover peaks (hopefully)
* @return {array of integers} peaks - indices of local peaks in @param arr.
*/
const localPeaks = (arr) => {
const peaks = [];
arr.forEach((element, index) => {
const prevIndex = index - 1;
const nextIndex = index + 1;
if (prevIndex >= 0 && nextIndex < arr.length) {
if (element > arr[prevIndex] && element > arr[nextIndex]) {
peaks.push(index);
}
}
});
return peaks;
};
console.log(localPeaks([4, 6, 5, 9, 11, 3, 90, 45])); // [1, 4, 6]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment