Find matching pairs in two arrays

Hi folks,

I'm a long time user of max, but a maxscript newbie. I'm trying to write a script that constrains objects together to aid in the rigging process. So far I've been able to filter my object selection into two arrays based on prefixes. Where I'm finding real difficulty is in comparing the two arrays to find matches, exposing the matched object pairs and assigning them to variables that I can work with.

My approach may be totally inefficient, as what I'm doing so far is:

collect selection into two arrays, one for master and one for slave objects based on name prefix.

remove the ID prefix from the object names and collect to two new arrays which should have some identically named entries now which allows me to match them up.

Create a loop that: searches the slave array for each entry in the master array - where it find a matching string, output the Index for the match in both arrays. Take the Index numbers and use them to identify the corresponding objects in the original arrays and assigns these object to variables which are then passed through the final step of constraining one to the other.

So there's probably a way more efficient way than what I'm doing with so many arrays and attempting to pass index values back and forth. It feels about as graceful as a rhino right now. If anyone has any suggestions on improving this, I'd be very grateful to hear them! :-D But efficiency takes a back seat to getting the script to work at all right now, so any help would be awesome! ;-)

The code so far is as follows - getting the arrays ready all works, but when it comes to finding matches and storing the index values, I'm way out of my depth, and I haven't found anything I can copy-paste from the internet either ;-)

(--collect selected objects to arrays, sort by prefix
CTRLObjectArray = for i in (selection as array) where (matchpattern pattern:"CTRL_*") collect i
CTRLNameArray = for i in CTRLObjectArray collect
BoneObjectArray = for i in (selection as array) where (matchpattern pattern:"BN_*") collect i
BoneNameArray = for i in BoneObjectArray collect
(--rename arrays to remove prefix
MasterTextID = "Ctrl_"
SlaveTextID = "Bn_"
CTRLNameTrimArray = for i in CTRLNameArray collect i = trimleft i MasterTextID
BoneNameTrimArray = for i in BoneNameArray collect i = trimleft i SlaveTextID)
( -- compare names from first array to second and extract index number for both arrays on match
for i in CTRLNameTrimArray do
    for o in BoneNameTrimArray do
    IndexCollect = for index=1 to BoneNameTrimArray.count where o == i collect index