Someone posted here a neat little function called 'closesttarget.sqs'. I took it in use right away. It's an excellent way to find out the nearest object from an array and in a script you can ask if the result distance to you is less or greater than something or if the returned object is someone who you want it to be.. and have the script to continue or loop.. or whatever you want.
I'm not at home right now, but when I get there I can find out who it was that made the function and kindly distributed it.
The nearestobject might work for you too. I haven't ever used though.