How get the index of an object in an array?

Your code not finding nearest, after it find current distance < nearest its break For Each Loop.

here the answer for your question