This is very basic, but for some reason, I can't figure out why I'm not able to return null when there are not any non-consecutive numbers in an array. My code works fine when the array is not totally consecutive:
function firstNonConsecutive(arr) {
for (let i = 0; i < arr.length; i++) {
if (arr[i + 1] - arr[i] !== 1) {
return arr[i + 1];
}
}
return null;
}
console.log(firstNonConsecutive([ 0, 1, 2, 3, 4, 6, 7, 8, 9 ]));
But if the array is consecutive, i.e. like this:
function firstNonConsecutive(arr) {
for (let i = 0; i < arr.length; i++) {
if (arr[i + 1] - arr[i] !== 1) {
return arr[i + 1];
}
}
return null;
}
console.log(firstNonConsecutive([ 6, 7, 8, 9, 10, 11, 12 ]));
You can see that it returns undefined instead of null. Why isn't it returning null? The return is outside of the for-loop.
I tried to create an initial check to see if the array is not consecutive, like this:
function firstNonConsecutive(arr) {
let newArr = [];
for (let j = arr[0]; j < arr[arr.length - 1]; j++) {
newArr.push(j);
}
//check if arr does not contain consecutive characters
if (String(arr) !== String(newArr)) {
for (let i = 0; i < arr.length; i++) {
if (arr[i + 1] - arr[i] !== 1) {
return arr[i + 1];
}
}
}
else {
return null;
}
}
console.log(firstNonConsecutive([ 0, 1, 2, 3, 4, 6, 7, 8, 9 ]));
But it did not make a difference. Any ideas?
i < arr.lengthand thenarr[i + 1]will be undefined. you will wanti < arr.length - 1arr[i + 1], which means the last iteration's test will always fail, then returnarr[i + 1]which isundefined.