Find the closest number in a Collection

FriFlo's icon

Let's say I have a collection (1 - 4) with the values 40, 42, 54, 60. I want to find out, which index number is closest to a specific value. So, if the incoming value would be 61, the patch should output index 4, because 60 is closest to 61.
Does anyone happen to know a solution to this problem?
If the incoming value would be 41, there is a problem, because it is just as close to index 1 as it is to index 2. In this case I would like it to choose randomly or either the higher or lower index. All would be fine, just not both of them.

Tj Shredder's icon

This is out of my St.ools collection:

save the p as closest, and then give it an argument. You can also get the complete St.ools here:

Max Patch
Copy patch and select New From Clipboard in Max.