Array question
Moderators: FourthWorld, heatherlaine, Klaus, kevinmiller, robinmiller
Array question
Assume an array where every key/value pair is unique.
Given the value of an array element, find the corresonding key.
Is there some nifty function for this that I as a newbie don't know or do I have to cycle through the entire array to find the match?
TIA,
Kai
Given the value of an array element, find the corresonding key.
Is there some nifty function for this that I as a newbie don't know or do I have to cycle through the entire array to find the match?
TIA,
Kai
Hi Kai,
sorry, no nifty function
But you could use a nifty trick using the "combine" function to extract the "key" from the array like this:
Given "tArry" is your array and "unique_value" is the value of the unknown key you are looking for.
...
combine tArray by CR and TAB
## This will turn your array into a CR separated list of
## "key TAB value" lines
put lineoffset(TAB & "unique_value",tArray) into tLine
set itemdel to TAB
put item 1 of line tLine of tArray into finally_found_the_fricking_key
...
Et voila, now you finally found the fricking key
Hope that helps.
Best from germany
Klaus
sorry, no nifty function

But you could use a nifty trick using the "combine" function to extract the "key" from the array like this:
Given "tArry" is your array and "unique_value" is the value of the unknown key you are looking for.
...
combine tArray by CR and TAB
## This will turn your array into a CR separated list of
## "key TAB value" lines
put lineoffset(TAB & "unique_value",tArray) into tLine
set itemdel to TAB
put item 1 of line tLine of tArray into finally_found_the_fricking_key
...
Et voila, now you finally found the fricking key

Hope that helps.
Best from germany
Klaus
Code: Select all
function getKeyOfValue theArray, theValue
repeat for each line currentKey in the keys of theArray
if theArray[currentKey] = theValue then return currentKey
end repeat
end getKeyOfValue
xApple's solution is fine, but just to show that it can be done with elements:
The advantage of this would be that you don't need to look up the element after getting the key first. I don't know what is faster though.
Best,
Mark
Code: Select all
on mouseUp
-- make an array
repeat with x = 1 to 10
put numtochar(x+96) into myArray["k" & x]
end repeat
-- search for key of letter f
put 0 into myCounter
repeat for each element myElement in myArray
add 1 to myCounter
if myElement is "f" then exit repeat
end repeat
put line myCounter of the keys of myArray
end mouseUp
Best,
Mark
The biggest LiveCode group on Facebook: https://www.facebook.com/groups/livecode.developers
The book "Programming LiveCode for the Real Beginner"! Get it here! http://tinyurl.com/book-livecode
The book "Programming LiveCode for the Real Beginner"! Get it here! http://tinyurl.com/book-livecode