View Full Version : Sorting Multidimensional Arrays

02 February 2009, 08:30 PM
Hello everyone!

I need some help with Maxscript, the situation is the following:

I have a multidimensional array which has strings, integers, booleans and so on in different sub-arrays.

For example:
multidim = #(#("John","Paul","Sam","Andy"),#(1,2,3,4),#(true,true,false,false)

I would like to sort the multidimensional array by names keeping the original structure. In this case I would like see the following:

multidim = #(#("Andy","John","Paul","Sam"),#(4,1,2,3),#(false,true,true,false)

I would really appreciate any help, thank you!

02 February 2009, 08:09 PM
May I ask a mod to move my thread to 3DSmax/Maxscript area? I'm new here, I guess I posted my question in the wrong place, sorry. Thank you!

02 February 2009, 01:49 PM

You could create an index array based on the 1st array sort something like:

MyArray= #(#("John","Paul","Sam","Andy"),#(1,2,3,4),#(true,true,false,false))
-- Make a copy of the 'Names' array
tmpArray=Deepcopy MyArray[1]
sort tmpArray
-- Create the sorted Index array
SortedIndexArray = for i in tmpArray collect (findItem MyArray[1] i)
-- Copy the original array
tmpArray=Deepcopy MyArray
-- re-order the elements of the copy accordin g to the original
for j=1 to MyArray.count do
for i =1 to SortedIndexArray.count do
-- copy the sorted array back to original

02 February 2009, 03:57 PM
This can be done with QSORT() too:

fn compareFN v1 v2 valArray: =
if valArray[v1] > valArray[v2] then 1 else -1

multidim = #(#("John","Paul","Sam","Andy"),#(1,2,3,4),#(true,true,false,false))

indexArray = for i = 1 to multidim[1].count collect i
qsort indexArray compareFN valArray:multidim[1]

newArray = for j in multidim collect
for i in indexArray collect j[i]


--> #(#("Andy", "John", "Paul", "Sam"), #(4, 1, 2, 3), #(false, true, true, false))

02 February 2009, 06:28 PM
newArray = for j in multidim collect
for i in indexArray collect j[i]

Snappy! :)

@Vicky, I suppose it must go without saying, though, that if at all possible, it would be better to structure your data as records in the first place? i.e.

struct person (name,number,isSomethingBoolean)

which would leave much less room for error / spaghetti , if the code depending on it is of more than trivial length. But you probably have good reasons for doing it this way.

02 February 2009, 01:38 AM
Thank you guys!! You helped me greatly!

CGTalk Moderation
02 February 2009, 01:38 AM
This thread has been automatically closed as it remained inactive for 12 months. If you wish to continue the discussion, please create a new thread in the appropriate forum.