06272005, 05:25 AM

#1

Registered User
Join Date: Jun 2005
Location: New York
Posts: 9

Array: how do I sort multidimensional numeric array in MX?
I need some help on how to sort an array with nested arrays of matched numbers: one nested array holds xcoordinates and the other nested array holds ycoordinates. The position of each x,y pair is matched, so if I use a typical numerical sorting function, I succeed only in sorting one array or the other, and I undo the relationship.
I describe my arrays below with example x,y coords, and although I may be heading in the wrong direction, I included the function that I know works to sort either one or the other array:
[as]
mySort = function(a,b) {
return ab;
}
var x= new Array(12,21,13,48,33);
var y= new Array(6, 99, 7, 2, 2);
var xy = new Array(x,y)
xy.sort(mySort);
//output: 13,12,21,33,48,6,99,7,2,2;
//(only first nested array of xy sorts, so nested arrays lose their relationship)
I need to output: 13,12,21,33,48,7,6,99,2,2
/[as]
The arrays don't have to be nested. I would be happy to be able to sort the x array and have the y array be sorted by the x array.
Last edited by calculus; 06272005 at 05:36 AM.



06272005, 07:31 AM

#2

OffLine
Join Date: Aug 2004
Location: Ibiza/Spain language :Hungarian/German/ abit English
Posts: 6,539

hi and welcome to As.Org
ActionScript Code:
XY = [{x:12, y:6}, {x:21, y:99}, {x:13, y:7}, {x:48, y:2}, {x:33, y:2}];
for (a=0; a<XY.length; a++) {
trace(XY[a].x+" "+XY[a].y);
}
XY.sortOn("x");
trace("After Sort");
x=[]
y=[]
for (a=0; a<XY.length; a++) {
trace(XY[a].x+" "+XY[a].y);
x.push(XY[a].x)
y.push(XY[a].y)
}
xy=[x,y]
trace(xy)



06272005, 03:51 PM

#3

Registered User
Join Date: Jun 2005
Location: New York
Posts: 9

Arrays to nested arrays problem
Thanks, Xeef
I appreciate your help  having the nested array in that style did the trick!
Now I'm flummoxed as to how to convert my two simple arrays into the nested style that your solution starts with: XY = [{x:12, y:6}, etc.]
I tried several ways to construct the nested array style you used, and I feel I am close with the following, but no cigar:
ActionScript Code:
v = (12,21,13,48,33);
w = (6,99,7,2,2);
VW = [{}];
for (a=0; a<v.length; a++) {
VW[a].v.push(v[a]);
VW[a].w.push(w[a]);
}
for (a=0; a<VW.length; a++) {
trace(VW[a].v+" "+VW[a].w);
}
//no output
//I need the output: VW = [{v:12, w:6}, {v:21, w:99}, {v:13, w:7}, {v:48, w:2}, {v:33, w:2}];



Thread Tools 

Display Modes 
Rate This Thread 
Linear Mode


Posting Rules

You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
HTML code is Off



All times are GMT. The time now is 01:11 PM.
///

