Just as the title says – I’m trying to find the first empty (missing) number (hole) in an array using for-loop or, if the array is sequential and starting from 1 through 7 for example, I’ll need the next integer after the last array item, in this case 8.
Need only one hole per whole iteration returning the found value.
My logic is ok when it comes to the first condition (array starting with a value higher than 1) but the from the next to conditions the last one is always picked up.
In a nutshell:
- in an array of [2,3,4,5,6,7] I need "1" and I get it;
- in an array of [1,2,3,4,6,7] I need "5" but I get "8".
- in an array of [1,2,3,4,5,6,7] I need "8" and I get it.
const numbers = [1, 2, 3, 4, 6, 7];
document.getElementById("demo").innerHTML = numbers;
let hole;
holeFinder()
function holeFinder() {
for (let i = 0; i < numbers.length; i++) {
if (numbers[0] > 1) {
/* console.log(numbers[0]) */
hole = 1;
document.getElementById("demo").innerHTML += "<br>1: hole: " + hole;
return hole;
}
if (numbers[i] > 1) {
if ((numbers[i] - numbers[i - 1]) > 1) {
hole = (numbers[i - 1] + 1)
document.getElementById("demo").innerHTML += "<br>2: hole: " + hole;
return hole;
}
if ((numbers[i] - numbers[i - 1]) == 1) {
hole = numbers[numbers.length - 1] + 1;
document.getElementById("demo").innerHTML += "<br>3: hole: " + hole;
return hole;
}
}
}
}
<h2>for loop method for finding non-sequential slots (holes) in an array</h2>
<p id="demo"></p>
What’s wrong with my logic?
>Solution :
You can do something like this
const arr1 = [1, 2, 3, 4, 6, 7]
const arr2 = [1, 2, 4, 5, 6, 7]
const arr3 = [1, 2, 3, 4, 5, 6, 7]
const findHole = arr => {
for(let i = 0; i < arr.length; i++){
if(arr[i] !== i + 1){
return i + 1
}
}
return arr.length + 1
}
console.log(findHole(arr1))
console.log(findHole(arr2))
console.log(findHole(arr3))