Finding the smallest positive integer not present in an array in JavaScript


We are required to write a JavaScript function that takes in array of integers as the first and the only argument.

Our function should find and return that smallest positive integer which is not present in the array.

For example −

If the input array is −

const arr = [4, 2, -1, 0, 3, 9, 1, -5];

Then the output should be −

const output = 5;

because 1, 2, 3, 4 are already present in the array and 5 is the smallest positive integer absent from the array.

Example

Following is the code −

const arr = [4, 2, -1, 0, 3, 9, 1, -5];
const findSmallestMissing = (arr = []) => {
   let count = 1;
   if(!arr?.length){
      return count;
   };
   while(arr.indexOf(count) !== -1){
      count++;
   };
   return count;
};
console.log(findSmallestMissing(arr));

Output

Following is the console output −

5

Updated on: 19-Jan-2021

714 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements