CMedina CMedina - 1 year ago 50
jQuery Question

Validate numbers consecutives in array

I have a array:

var aNumbers = [1,2,1,3,4,4,5];

I need validate two conditions:

1. First, I need to know if the array contains a number, I have a function that find the element. (No problem, It's working!)

function include(arr,obj) {
return (arr.indexOf(obj) != -1);


2. Second , I need one function to validate the number in sequence, something like this:

function consecutive(arr,obj){

The result expected....


In summary: I need to add a number that exists in my array or be consecutive to the maximum.

if(include(aNumbers, newNumber)){
}else if(consecutive(aNumbers, newNumber)){
alert('Number not valid!!!');

I need help with my function to validate consecutive!!!

Answer Source

Assuming array is sorted

function consecutive(arr,obj){
    return arr[arr.length - 1] + 1 === obj;

If not

function consecutive(arr,obj){
    return Math.max.apply(Math, arr) + 1 === obj;