Find missing item from 1..N items array

  • A+
Category:Languages

I was asked to find the missing number from 1..N array.

For instance, for array: let numArr = [2,4,6,8,3,5,1,9,10]; the missing number is 7

let numArr=[2,4,6,8,3,5,1,9,10]; numArr.sort(function(a,b){  //sort numArr   return a-b; });  let newNumArr=[]; for(let i=1;i<=10;i++){   newNumArr.push(i); }  for(let i=0;i<newNumArr.length;i++){  //compare with new arr   if(newNumArr[i] !== numArr[i]){     console.log('The missing num is:'+newNumArr[i]);  //The missing num is:7     break;   } } 


You can use MAP and FILTER to find out the missing number in seperate array

const numArr = [2, 4, 6, 8, 3, 5, 1, 9, 10]; const missingNumberArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map(number => {     if (!numArr.includes(number)) {         return number;     } }).filter(y => y !== undefined); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: