- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements
To Continue Learning Please Login
Login with Google