Sorting Arrays
Bob Sneidar
bobsneidar at iotecdigital.com
Tue Aug 8 19:15:08 EDT 2023
Has anyone come across a need to sort a numbered array by the values of the different keys? Here you go. Keep in mind that there is no error checking so I have no idea what would happen if you provided a sort key that didn’t exist in the array.
on sortNumberedArray @pArrayDataA, pSortKeys
/*
Provide a numbered array of key value pairs and a comma delimited list of the sort order you want.
Ex. "filename,version numeric descending".
The result will be numbered array resorted by the sort order you provide.
*/
put the keys of pArrayDataA into tKeyList
sort tKeyList numeric ascending
put the number of items of pSortKeys into tSortKeyCount
-- convert the sort keys to an array
repeat with i = the number of items of pSortKeys down to 1
put item i of pSortKeys into tSortIndex
repeat with x = the number of words of tSortIndex down to 1
put word x of tSortIndex into tKeyWord
switch
case tKeyWord is among the items of "asc,ascending,desc,descending"
put tKeyWord into tSortKeysA [i] ["sortorder"]
break
case tKeyWord is "International,Numeric,datetime,text,binary"
put tKeyWord into tSortKeysA [i] ["sorttype"]
break
default
put word 1 to x of tSortIndex into tSortKeysA [i] ["sortvalue"]
end switch
end repeat
end repeat
-- build a comma delimited list of sort keys from the passed array
put the keys of pArrayDataA into tInputKeyList
sort tInputKeyList numeric ascending
repeat for each line tLine in tInputKeyList
put the keys of tSortKeysA into tSortKeyList
sort lines of tSortKeyList numeric
repeat for each line tSortLine in tSortKeyList
put tSortKeysA [tSortLine] ["sortvalue"] into tSortValue
put pArrayDataA [tLine] [tSortValue] into item tSortLine of line tLine of tSortValueList
end repeat
put "," & tLine after tSortValueList
end repeat
-- sort the list
put the keys of tSortKeysA into tSortKeyList
sort tSortKeyList numeric descending
repeat for each line tKey in tSortKeyList
put "sort lines of tSortValueList" && tSortKeysA [tKey] ["sortorder"] && tSortKeysA [tKey] ["sorttype"] && \
"by item" && tkey && "of each" into tSortCommand
do tSortCommand
end repeat
-- convert the list back to an array
repeat for each line tLine in tSortValueList
add 1 to tArrayCounter
put item -1 of tLine into tArrayIndex
put pArrayDataA [tArrayIndex] into tOutArrayA [tArrayCounter]
end repeat
put tOutArrayA into pArrayDataA
end sortNumberedArray
Bob S
More information about the use-livecode
mailing list