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
Checking if each member (excluding the first one) minus the previous one is equal to 1 should work out for you.
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: