Hello,

So I am trying to solve this task using JavaScript code. It goes like this: Find the smallest positive integer that is not a part of the same array. For example: for [2,1,3] it should print 4. For [-3,-1,2,5,6], it should print 1. This is my code, however I can’t seem to figure out what did I do wrong:

// this function checks if a number is an element of an array

function check(array, element){
let statement;

``````for (let i = 0; i<array.length;i++){
if (element!==array[i]){

statement = false;
}
else if (element===array[i]){
statement = true;
break;
}
}
return statement;
``````

}
// this function removes an element from an array
function removeItemOnce(arr, value) {
var index = arr.indexOf(value);
if (index > -1) {
arr.splice(index, 1);
}
return arr;
}

// this function returns the smallest positive integer from an array that is not
// an element of an array in the first place

function min(array){
let b = Math.min.apply(Math, array);
while(array.length>0){

``````    // we start from the smallest element and check whether it is positive
// and part of an array as the number needs to be
if (check(array,b)===false && b>0){
return b;
break;
}
else if(b=<0){
continue;
}
array = removeItemOnce(array,b);
b+=1;
}
``````

}

let arr = [-1,-3,-5,2]; // it should print 1
console.log(min(arr));

Different concept without functions:

let arr=[-3,-1,2,5,6] //delete negative numbers const posArr=arr.filter(num => num > 0); //output [2,5,6] for (i = 1; i <= posArr.length+1; i++) { if (posArr.indexOf(i) === -1) { console.log(i); break; } }
1 Like

I think you have to increase the value of b before you continue to the next iteration in this case,
so there should be a `b+=1;` just before the `continue`

Hi, thank you so much. This method is a lot more simpler than the initial way. Many Thanks!

This is not fully tested but passes basic tests…

``````def f(a):
a = [b for b in sorted(a) if b > 0]
n = 0
for m in a:
if m > n + 1:
return n + 1
n = m
return n + 1

``````
``````>>> f([-3, -1, 2, 5, 6])
1
>>> f([-3, -1, 1, 2, 3, 4, 5, 6])
7
>>> f([-3, -1, 1, 2, 5, 6])
3
>>> f([6, -3, 3, 5, 2, -1, 4, -2, 1])
7

``````

Mind, it will need to be ported from Python to JS.

Okay, here is the ported code…

``````const f = function(a) {
const g = function(s) {
return s.sort((a, b) => a - b)
}
a = g(a.filter(b => b > 0))
let n = 0
for (let m of a) {
if (m > n + 1) {
return n + 1
}
n = m
}
return n + 1
}
``````
`````` > f([-3, -1, 1, 2, 3, 4, 5, 6])
<- 7
> f([-3, -1, 2, 5, 6])
<- 1
> f([-3, -1, 1, 2, 5, 6])
<- 3
> f([6, -3, 3, 5, 2, -1, 4, -2, 1])
<- 7
``````
2 Likes

Thank you very much, I appreciate it!

1 Like