To find missing numbers in a given array of numbers, you can sort the array and then loop through it, checking if the current number is equal to the expected number. If not, the missing numbers can be added to an array.
Here’s an example:
let array = [3, 7, 1, 5, 4, 6, 9, 10];
array.sort((a, b) => a - b);
let missing = [];
let expected = array[0];
for (let i = 0; i < array.length; i++) {
if (expected !== array[i]) {
while (expected < array[i]) {
missing.push(expected);
expected++;
}
}
expected++;
}
console.log(missing);
In this example, the input array [3, 7, 1, 5, 4, 6, 9, 10]
is sorted using array.sort((a, b) => a - b)
. The code then loops through the sorted array, checking if the current number is equal to the expected number expected
. If not, the missing numbers are added to the missing
array using a while
loop. Finally, the missing numbers are logged using console.log(missing)
.
+ There are no comments
Add yours