• Status: Solved
• Priority: Medium
• Security: Public
• Views: 255

# get sorted column for 2D array

Need a one-liner for extracting a single column from a 2D array, provided the index.  The returned array should be sorted (numerically).

I found code on EE for sorting a single column but it returns the entire 2D array with column i sorted.

@ary = (
[4,5,8],
[2,10,5],
[8,13,7]
);

\$i = 0;
@sorted = sort {\$a->[\$i]<=>\$b->[\$i]} @ary;

I just want column i sorted and returned.
0
mock5c
2 Solutions

Commented:

@ary = (
[4,5,8],
[2,10,5],
[8,13,7]
);

\$i = 0;
@sorted = sort map {\$_->[\$i]} @ary;
0

Commented:
If you wanted the second column to sort right you would add this to ps15's code.

@ary = (
[4,5,8],
[2,10,5],
[8,13,7]
);

\$i = 1;
@sorted = sort {\$a <=> \$b} map {\$_->[\$i]} @ary;

print "@sorted";

That is unless you rather would have 10 13 5 then omit {\$a <=> \$b}
0

Author Commented:
I didn't test every case (only the first and last columns) so I accepted ps15's answer even though the 2nd column did not sort numerically.  tone28's suggestion does sort all columns correctly.  I'm going to contact support and ask them to assign extra points and assisted answer for tone28.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.