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 −
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