Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find missing item from 1..N items array

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;
  }
}
like image 347
Dangur Avatar asked Dec 10 '22 06:12

Dangur


1 Answers

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);
like image 59
Praveen Kumar Avatar answered Dec 12 '22 18:12

Praveen Kumar