skip to Main Content

I am trying to validate if an array of numbers is an incremental sequence with no jumps between numbers. For example:

const items = [1,2,3,4] // Should return true
const items = [1,2,4] // Should return false - jumps from 2 to 4
const items = [5,6,7] // Should return true

The array doesn’t always starts at 1, like the above example which returns true that starts at 5. How could I write a function to validate this so that it returns true or false depending on if the sequence has jumps?

Thanks in advance.

3

Answers


  1. function isIncrementalSequence(arr) {
      if (arr.length <= 1) return true; // Single element or empty array is considered a sequence
    
      for (let i = 1; i < arr.length; i++) {
        if (arr[i] !== arr[i - 1] + 1) {
          return false; // If there's a jump, return false
        }
      }
    
      return true; // No jumps found, return true
    }
    
    // Test cases
    console.log(isIncrementalSequence([1, 2, 3, 4])); // true
    console.log(isIncrementalSequence([1, 2, 4]));    // false
    console.log(isIncrementalSequence([5, 6, 7]));    // true
    
    Login or Signup to reply.
  2. Checking if each member (excluding the first one) minus the previous one is equal to 1 should work out for you.

    const items = [1,2,3,4] // Should return true
    //2 - 1 = 1, 3 - 2 = 1,...
    const items = [1,2,4] // Should return false
    //4 - 2 = 2 -> false
    const items = [5,6,7] // Should return true
    // 6 - 5 = 1,...
    
    Login or Signup to reply.
  3. You can write a function that loops over the array and compares the current item in the array to the previous item. If the response is not equal to one, break the function and return false.
    See function below:

    const isArrayIsInSequence = (items: number[]) => {
      if (items.length <= 1) return true;
    
      for (let i = 1; i < items.length; i++) {
        if (items[i] - items[i - 1] !== 1) {
          return false;
        }
      }
    
      return true;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search