The key thing to note here is that the numbers are sequential, and as such there's an expectation that the input array is sorted to begin with. In other words, since the numbers are incrementing by one at each index, they'll by definition be sorted in ascending order.
Knowing that, we can do a simple iteration through the array, and check that the difference between the current number and the one before it is 1
.
The difficult part is when there are gaps larger than 1
. For example:
[3, 4, 7, 8]
When we get to 7
, we'll notice that the difference between it and the last number (4
) is 3
, which is more than just a gap of 1
.
Knowing that, we can simply use a while
loop to append the appropriate numbers in the missing
array while keeping a counter. Let's call this counter diff
. It'll track how many numbers we have to append before we close the gap.
xxxxxxxxxx
const numArr = [3, 4, 7, 8];
​
const missing = [];
​
for (let i in numArr) {
// get the size of the gap
let x = numArr[i] - numArr[i - 1];
// start filling in the gap with `1`
let diff = 1;
// while there's still a gap, push the correct numbers
// into `missing`, calculated by the number + diff
while (diff < x) {
missing.push(numArr[i - 1] + diff);
diff++;
}
}
​
console.log(missing);