- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Strictly increasing or decreasing array - JavaScript
In Mathematics, a strictly increasing function is that function in which the value to be plotted always increase. Similarly, a strictly decreasing function is that function in which the value to be plotted always decrease.
We are required to write a JavaScript function that takes in an array of numbers and returns true if it’s either strictly increasing or strictly decreasing, otherwise returns false.
Example
Following is the code −
const arr = [12, 45, 6, 4, 23, 23, 21, 1]; const arr2 = [12, 45, 67, 89, 123, 144, 2656, 5657]; const sameSlope = (a, b, c) => (b - a < 0 && c - b < 0) || (b - a > 0 && c - b > 0); const increasingOrDecreasing = (arr = []) => { if(arr.length <= 2){ return true; }; for(let i = 1; i < arr.length - 1; i++){ if(sameSlope(arr[i-1], arr[i], arr[i+1])){ continue; }; return false; }; return true; }; console.log(increasingOrDecreasing(arr)); console.log(increasingOrDecreasing(arr2));
Output
Following is the output in the console −
false true
Advertisements