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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With