Finding one missing number in a scrambled sequence using JavaScript


Problem

We are required to write a JavaScript function that takes in an array of numbers containing numbers from 1 to n.

The problem is that one number from the array goes missing and the array is not sorted as well. Our function should find and return that one number missing from the array.

Example

Following is the code −

 Live Demo

const arr = [4, 7, 1, 8, 9, 5, 2, 3];
const findMissing = (arr = []) => {
   const sumArr = arr.reduce((acc, val) => acc + val);
   const { length: len } = arr;
   const sumFirst = (len + 1) * (len + 2) * .5;
   const missing = sumFirst - sumArr;
   return missing;
};
console.log(findMissing(arr));

Output

6

Updated on: 19-Apr-2021

136 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements