How to check if an array is all increasing or decreasing and the gap between numbers is 1, 2 or 3 in JavaScript

1 Answer

0 votes
function isArraySortedAndValidGap(arr) {
    if (arr.length < 2) return true;

    const increasing = arr[1] > arr[0];
    for (let i = 1; i < arr.length; ++i) {
        const diff = arr[i] - arr[i - 1];
        if (diff !== 1 && diff !== 2 && diff !== 3 && diff !== -1 && diff !== -2 && diff !== -3) {
            return false;
        }
        if ((increasing && diff <= 0) || (!increasing && diff >= 0)) {
            return false;
        }
    }
    
    return true;
}

const arr1 = [1, 2, 3, 5, 8, 11, 14, 15];
if (isArraySortedAndValidGap(arr1)) {
    console.log("Array is sorted and has valid gaps");
} else {
    console.log("Array is not sorted or gaps are invalid");
}

const arr2 = [15, 14, 11, 8, 5, 3, 2, 1];
if (isArraySortedAndValidGap(arr2)) {
    console.log("Array is sorted and has valid gaps");
} else {
    console.log("Array is not sorted or gaps are invalid");
}


 
 
/*
run:

Array is sorted and has valid gaps
Array is sorted and has valid gaps
 
*/

 



answered Jan 12, 2025 by avibootz
...