'Return missing number in array of integers 1 - 9 [closed]

I ran the code using different arrays missing a number between 1 - 9, but it kept returning -1.

function findMissing(arrOfNumbers) {
  const integers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
  for (let index = 0; index < arrOfNumbers.length; index++) {
    if (integers[index] !== arrOfNumbers[index]) {
      return integers[index];
    }
    return -1;
  }
}

console.log(findMissing([0, 1, 3, 4, 6, 7, 8, 9])); //returns -1 instead of 5


Solution 1:[1]

If I understood the problem, you want missing elements from array 2. if so, simply use,

arr1.filter(x=> !arr2.includes(x));

In your case

const array1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
const array2 = [0, 1, 3, 4, 6, 7, 8, 9];
const result = array1.filter(x=> !array2.includes(x)); // returns 2 , 5

console.log(result)

Solution 2:[2]

You can spread the array over an object and compare the key and value pairs of the object. If key and value are different then that means some value is missing in the input array that is out of range. Note the use of !=, it is intentional to compare values and not types.

function findMissing(arrOfNumbers) {
  const obj = {...arrOfNumbers};
  for(const [key, val] of Object.entries(obj)) {
    if(key != val) {
      return key;
    }
  }
  return -1;
}

// returns 2 since it is the first missing value in the order
console.log(findMissing([0, 1, 3, 4, 6, 7, 8, 9])); 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Parag Diwan
Solution 2