
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
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
Finding all peaks and their positions in an array in JavaScript
Build Up
Suppose we have the following array in JavaScript −
const arr = [4, 3, 4, 7, 5, 2, 3, 4, 3, 2, 3, 4];
If we plot the points of this array on y-axis with each adjacent point being unit distance away on x-axis, the graph will look like this −
This graph clearly shows that there exist two local maxima (peaks) in this array at index 3 and 7 with values 7 and 4 respectively.
Problem
We are required to write a JavaScript function that takes in an array of integers, arr, as the first and the only argument.
Our function is supposed to return an object that contains two properties, maximas, and positions.
Both these properties will be arrays, and the maxima array will contain the value of local maximas in the array and the positions array will contain their corresponding indices.
For example, if the input to the function is −
Therefore, for the above array, the output should look like −
const output = { maximas: [7, 4], positions: [3, 7] };
Example
Following is the code −
const arr = [4, 3, 4, 7, 5, 2, 3, 4, 3, 2, 3, 4]; const findMaxima = (arr = []) => { let positions = [] let maximas = [] for (let i = 1; i < arr.length - 1; i++) { if (arr[i] > arr[i - 1]) { if (arr[i] > arr[i + 1]) { positions.push(i) maximas.push(arr[i]) } else if (arr[i] === arr[i + 1]) { let temp = i while (arr[i] === arr[temp]) i++ if (arr[temp] > arr[i]) { positions.push(temp) maximas.push(arr[temp]) } } } } return { maximas, positions }; }; console.log(findMaxima(arr));
Output
Then the output should be −
{ maximas: [ 7, 4 ], positions: [ 3, 7 ] }
- Related Questions & Answers
- Finding all possible combinations from an array in JavaScript
- Finding all possible subsets of an array in JavaScript
- How to insert an element into all positions in an array using recursion - JavaScript?
- Finding all the longest strings from an array in JavaScript
- Finding all duplicate numbers in an array with multiple duplicates in JavaScript
- How to find all adverbs and their positions in a text using python regular expression?
- Finding unlike number in an array - JavaScript
- Finding unique string in an array in JavaScript
- Finding the rotation of an array in JavaScript
- Finding the mid of an array in JavaScript
- Finding degree of subarray in an array JavaScript
- Finding matching pair from an array in JavaScript
- Finding confusing number within an array in JavaScript
- Finding Fibonacci sequence in an array using JavaScript
- Find and return array positions of multiple values JavaScript