CMedina CMedina - 5 months ago 6
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);
}

include(aNumbers,1);//true
include(aNumbers,6);//false


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

function consecutive(arr,obj){
//code
}


The result expected....

consecutive(aNumbers,6);//true
consecutive(aNumbers,7);//false


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

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


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

Answer

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;
}
Comments