w3resource

JavaScript: Missing number from an array

JavaScript Math: Exercise-83 with Solution

Find Missing Number in Array

Write a JavaScript program to find the missing number in a given array. There are no duplicates in the list.

Test Data:
([1,2,3,5,6,7]) -> 4
([2,3,4,5]) -> 1

Sample Solution:

JavaScript Code:

/**
 * Function to find the missing number in an array of consecutive integers.
 * @param {number[]} nums - The input array of consecutive integers.
 * @returns {number} - The missing number in the array.
 */
function test(nums) {
  // Iterate over consecutive integers up to the length of the input array + 1
  for (let n = 1; n <= nums.length + 1; n++) {
    // Check if the current integer is not found in the input array
    if (nums.indexOf(n) === -1) 
      // If the current integer is not found, return it as the missing number
      return n;
  }
}

// Test cases
// Assign value to nums
nums = [1, 2, 3, 5, 6, 7];
// Print the value of nums
console.log("nums = " + nums);
// Find the missing number in the said array
console.log("Missing number of the said array: " + test(nums));
// Repeat the above steps for a different value of nums
nums = [2, 3, 4, 5];
console.log("nums = " + nums);
console.log("Missing number of the said array: " + test(nums));

Output:

nums = 1,2,3,5,6,7
Missing number of the said array: 4
nums= 2,3,4,5
Missing number of the said array: 1

Flowchart:

JavaScript: Missing number from an array.

Live Demo:

See the Pen javascript-math-exercise-83 by w3resource (@w3resource) on CodePen.


For more Practice: Solve these Related Problems:

  • Write a JavaScript function that finds the missing number in a consecutive sequence by using the arithmetic series sum formula.
  • Write a JavaScript function that sorts an unsorted array of consecutive numbers and identifies the missing element.
  • Write a JavaScript function that iterates through an array and detects gaps between consecutive numbers.
  • Write a JavaScript function that uses the difference between expected and actual sums to determine the missing number.

Go to:


PREV : Mean of Digits in a Number.
NEXT : Sum of Two Highest Numbers in Array.

Improve this sample solution and post your code through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.