Say I have an array which holds the values [1,2,3,6,7].
How can I check the array to see if it holds 3 consecutive numbers. For example, the array above holds [1,2,3] so this would return false in my function.
var currentElement = null;
var counter = 0;
//check if the array contains 3 or more consecutive numbers:
for (var i = 0; i < bookedAppArray.length; i++) {
if ((bookedAppArray[i] != currentElement) && (bookedAppArray[i] === bookedAppArray[i - 1] + 1)) {
if (counter > 2) {
return true;
}
currentElement = bookedAppArray[i];
counter++;
} else {
counter = 1;
}
}
if(counter > 2){
return true;
} else{
return false;
}
This solution
2
,1
1
function consecutive(array) {
var i = 2, d;
while (i < array.length) {
d = array[i - 1] - array[i - 2];
if (Math.abs(d) === 1 && d === array[i] - array[i - 1]) {
return false;
}
i++;
}
return true;
}
document.write(consecutive([1]) + '<br>'); // true
document.write(consecutive([2, 4, 6]) + '<br>'); // true
document.write(consecutive([9, 8, 7]) + '<br>'); // false
document.write(consecutive([1, 2, 3, 6, 7]) + '<br>'); // false
document.write(consecutive([1, 2, 3, 4, 5]) + '<br>'); // false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With