Smallest valid member of array

Hello there. I have been wrestling with a bug for awhile now. I’m trying to find the lowest index of an array that is also x. X being a property I have set up.

Here is the code I’m using now. It works fine to a point. If I add, for instance, two objects to the array and then remove the first. “test[0] = null” smallest then equals two, it should be zero. If I remove the second “test[1] = null” then smallest equals zero.

 for(var f = 0; f < test.length; f ++){
		if(test[f] != null){
			smallest = test.length;
		}
	    if(f < smallest&&test[f] == null){
			
			smallest = f;
		} 
		
	}

any help would be greatly appreciated, I can’t for the life of me figure it out.

Cheers

If you simply are trying to find the lowest index in your test array, just jump out of the loop as soon as you have located your first non-null index.

You can do that by placing a break inside your first if statement, example:

if(test[f] != null){
             smallest = test.length;
             break;
    }

This will end the loop without executing the rest of its content. Be adviced! Some people say, it is bad practice others don’t.

Or you could instead just create an if-else statement, and assign your incremental variable f to the same value as test.length to get out of the loop.

 for(var f = 0; f < test.length; f ++){
       if(test[f] != null){
         smallest = test.length;
         f = test.length
       } else if (f < smallest&&test[f] == null){
         smallest = f;
       } 
}

This will make the (f < test.length) false and quit the loop as soon it reaches its end.
Be adviced when assigning index-values to null without cleaning up the array. In the long run the array can become long, and tangled and occupy more space.


Edit: Didn’t understand your question fully

Previous message:

As far as I can see here is the issue:

Case: test[0] = null

First run through of the loop does nothing:

  • if(test[0] != null) is false because test[0] is actually null
  • if(f < smallest&&test[f] == null) is also false, because f is NOT lesser than 0 (assuming you haven’t assigned smallest to any value before the test)

Second run through the loop:

  • (test[1] != null) is true, so smallest become test.Length

Solution: Your smallest variable, need to be a number lesser than 0, before entering the loop.