Check if an array is growing by the same margin in JavaScript

We are required to write a JavaScript function that takes in an array of numbers. Our function should return true if the difference between all adjacent elements is the same positive number, false otherwise.

Syntax

function growingMarginally(arr) {
    // Check if array has consistent positive differences
    // Return true/false
}

Example: Basic Implementation

The code for this will be ?

const arr = [4, 7, 10, 13, 16, 19, 22];
const growingMarginally = arr => {
    if(arr.length <= 1){
        return true;
    };
    const diff = arr[1] - arr[0];
    if(diff < 0){
        return false;
    }
    for(let i = 0; i < arr.length - 1; i++){
        if (arr[i+1] - arr[i] !== diff){
            return false;
        }
    }
    return true;
};
console.log(growingMarginally(arr));
true

Testing Different Cases

Let's test the function with various array types:

// Growing by same margin
console.log(growingMarginally([2, 5, 8, 11]));     // true (diff = 3)

// Not growing by same margin  
console.log(growingMarginally([1, 3, 6, 8]));      // false (diffs: 2, 3, 2)

// Decreasing array
console.log(growingMarginally([10, 7, 4, 1]));     // false (negative diff)

// Single element
console.log(growingMarginally([5]));               // true

// Empty array
console.log(growingMarginally([]));                // true
true
false
false
true
true

How It Works

The function follows these steps:

  1. Edge cases: Arrays with 0 or 1 elements return true
  2. Calculate difference: Find the difference between first two elements
  3. Check positivity: Return false if the difference is negative
  4. Validate consistency: Loop through remaining pairs to ensure all differences match

Alternative Approach Using every()

const growingMarginallyAlt = arr => {
    if (arr.length <= 1) return true;
    
    const diff = arr[1] - arr[0];
    if (diff <= 0) return false;
    
    return arr.every((val, i) => 
        i === 0 || arr[i] - arr[i-1] === diff
    );
};

console.log(growingMarginallyAlt([3, 6, 9, 12]));  // true
console.log(growingMarginallyAlt([1, 2, 4, 7]));   // false
true
false

Conclusion

This function efficiently checks if an array grows by a consistent positive margin by comparing adjacent differences. Both loop-based and functional approaches work effectively for this validation.

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

193 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements