How to find the missing number in an int array of 1 to 100 in JS

Overview

Consider an array of numbers from 1 to 100. In this array, duplicate elements are not allowed. Also, there is one number missing in this array. We will find that by following the steps provided below:

Step 1: Calculate the sum of numbers from 1 to 100 using the sum of natural numbers formula given below:

Step 2: Find the sum of the values present in the array.

Step 3: Subtract the sum of the elements of the array from the sum of 1 to 100 numbers. We'll get the missing number as a result.

Example

function findMissedNum(arrayOfNumbers, n = 100) {
if(arrayOfNumbers.length === n) {
console.log("no number is missed");
}
if(arrayOfNumbers.length < (n - 1) ) {
console.log("more than one number is missed")
}
let totalSum = (n * (n+1)) / 2;
let sumOfArray = 0;
for(let i of arrayOfNumbers){
sumOfArray += i;
}
return totalSum - sumOfArray;
}
// create an array with values 0 to 100
let arrayOfNumbers = Array.from( Array(101).keys())
// remove the 0th element
arrayOfNumbers.shift();
// now the array will 1 to 100
// remove the value at index 50.(means remove 51 from the array)
arrayOfNumbers.splice(50, 1)
// now the array is 1 to 100 but without the number 51
let missedNum = findMissedNum(arrayOfNumbers, 100);
console.log("The missing number is :", missedNum)

Explanation

  • Lines 1–16: We create a findMissedNum function that will find the missing number of an array using the above algorithm.
  • Line 18: We create a new array, arrayOfNumbers.
  • The Array(101) array returns an array with 101 empty elements.
  • On the created array, we call the keys method, which returns an array iterator object that contains the key of each index. In our case, iterator from is from 0 to 100.
  • We use the Array.from method with the array iterator as an argument. This method returns a new array with the values of the array iterator. We get an array with values 0 to 100.
  • Line 21: We use the shift method to remove the first element of the array. Now the array will be 1 to 100.
  • Line 26: We use the slice method to remove the element at index 50. Element 51 will be removed from the array.
  • Line 30: We call the findMissedNum method. This method returns the missing number 51 as result.