 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
JavaScript Program for Number of Local Extrema in an Array
JavaScript Program for the Number of local extrema in an array is a common problem in the field of computer science and data analysis. Local extrema are the peaks and valleys in a sequence of numbers.
In this article we are having two arrays, our task is to write a Javascript program for number of local extrema in an array.
 
 Example
Input: arr1 = [1, 2, 3, 2, 1, 4, 5, 6, 5, 4, 3, 2, 1]; First local extrema: 3, {2 < 3 > 2} Second local extrema: 1, {2 > 1 < 4} Third local extrema: 6, {5 < 6 > 5} Output: 3 Input: arr2 = [2, 4, 6, 8, 10]; Output: 0  Steps to Count Number of Local Extrema in Array
We will be following below mentioned steps for number of local extrema in an array. We will check for an element to be either greater than its both neighbour elements or to be smaller than both its neighbour elements. Both, the start and end element is not considered as local extrema as they have just one neighbour.
- We have declared two arrays, arr1 and arr2 and defined a function localExtrema() and passed an array arr as argument.
- Initialize a variable count to 0 to keep track of the number of local extrema.
- We have used for loop to iterate over elements of the array.
- For each element in the array, check if it is greater than its previous and next elements or lesser than its previous and next elements. If yes, then increment the count variable.
- After completing the loop, return the count variable as the number of local extrema in the array. The count is displayed in web console using console.log() method.
Example
Here is a complete example code implementing above mentioned steps for Number of local extrema in an array using for loop and if/else statement.
const arr1 = [1, 2, 3, 2, 1, 4, 5, 6, 5, 4, 3, 2, 1]; const arr2 = [2, 4, 6, 8, 10]; function localExtrema(arr) { let count = 0; for (let i = 1; i < arr.length - 1; i++) { if ((arr[i] > arr[i - 1] && arr[i] > arr[i + 1]) || (arr[i] < arr[i - 1] && arr[i] < arr[i + 1])) { count++; } } return count; } console.log("Number of local extrema in [" +arr1 +"] is: " +localExtrema(arr1)); console.log("Number of local extrema in [" +arr2 +"] is: " +localExtrema(arr2));  Output
Number of local extrema in [1,2,3,2,1,4,5,6,5,4,3,2,1] is: 3 Number of local extrema in [2,4,6,8,10] is: 0
Practice and learn from a wide range of JavaScript examples, including event handling, form validation, and advanced techniques. Interactive code snippets for hands-on learning.
