Finding the inclination of arrays in JavaScript

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.

In Mathematics, a strictly increasing function is that function in which the value to be plotted always increases. Similarly, a strictly decreasing function is that function in which the value to be plotted always decreases.

Understanding the Concept

An array has a consistent inclination when:

  • Strictly increasing: Each element is greater than the previous one
  • Strictly decreasing: Each element is less than the previous one

Example

Let's implement a function to check array inclination:

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

How It Works

The sameSlope helper function checks if three consecutive elements maintain the same direction (all increasing or all decreasing). The main function iterates through the array, ensuring all segments have consistent inclination.

Simplified Approach

Here's an alternative method that's easier to understand:

const checkInclination = (arr) => {
    if (arr.length <= 1) return true;
    
    let isIncreasing = true;
    let isDecreasing = true;
    
    for (let i = 1; i < arr.length; i++) {
        if (arr[i] <= arr[i-1]) isIncreasing = false;
        if (arr[i] >= arr[i-1]) isDecreasing = false;
    }
    
    return isIncreasing || isDecreasing;
};

// Test cases
console.log(checkInclination([1, 2, 3, 4]));     // true (increasing)
console.log(checkInclination([4, 3, 2, 1]));     // true (decreasing)
console.log(checkInclination([1, 3, 2, 4]));     // false (mixed)
console.log(checkInclination([2, 2, 2]));        // false (equal elements)
true
true
false
false

Comparison of Methods

Method Complexity Readability Performance
Slope checking Medium Complex Good
Flag-based Low High Excellent

Conclusion

The flag-based approach is simpler and more readable for checking array inclination. It efficiently determines if an array is strictly increasing or decreasing by tracking both possibilities simultaneously.

Updated on: 2026-03-15T23:19:00+05:30

169 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements