Strictly increasing or decreasing array - JavaScript

In Mathematics, a strictly increasing function is one where values always increase, while a strictly decreasing function has values that always decrease. In JavaScript, we can check if an array follows either pattern.

We need to write a function that takes an array of numbers and returns true if it's either strictly increasing or strictly decreasing, otherwise returns false.

Understanding the Logic

The key insight is to check if consecutive elements maintain the same slope (all increasing or all decreasing). We use a helper function sameSlope that compares three consecutive numbers to ensure they follow the same trend.

Example Implementation

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);

const increasingOrDecreasing = (arr = []) => {
    if(arr.length 

false
true

How It Works

The sameSlope function checks if three consecutive numbers have the same trend:

  • (b - a - both differences are negative (decreasing)
  • (b - a > 0 && c - b > 0) - both differences are positive (increasing)

The main function iterates through the array, checking each triplet of consecutive elements. If any triplet breaks the pattern, it returns false.

Alternative Approach

Here's a simpler approach that directly checks the entire array:

const isStrictlyIncreasingOrDecreasing = (arr) => {
    if (arr.length = arr[i-1]) isDecreasing = false;
    }
    
    return isIncreasing || isDecreasing;
};

console.log(isStrictlyIncreasingOrDecreasing([1, 2, 3, 4]));    // true
console.log(isStrictlyIncreasingOrDecreasing([4, 3, 2, 1]));    // true
console.log(isStrictlyIncreasingOrDecreasing([1, 3, 2, 4]));    // false
true
true
false

Conclusion

Both approaches effectively determine if an array is strictly increasing or decreasing. The second method is more intuitive and easier to understand, making it preferable for most use cases.

Updated on: 2026-03-15T23:18:59+05:30

479 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements