Solved

# get sorted column for 2D array

Posted on 2006-05-16
208 Views
Last Modified: 2010-03-05
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
Question by:mock5c
3 Comments

LVL 4

Accepted Solution

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

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

LVL 6

Assisted Solution

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 Comment

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

## Write Comment

Please enter a first name

Please enter a last name

We will never share this with anyone.

## Featured Post

Many time we need to work with multiple files all together. If its windows system then we can use some GUI based editor to accomplish our task. But what if you are on putty or have only CLI(Command Line Interface) as an option to  edit your files. I…
In the distant past (last year) I hacked together a little toy that would allow a couple of Manager types to query, preview, and extract data from a number of MongoDB instances, to their tool of choice: Excel (http://dilbert.com/strips/comic/2007-08…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
This video is in connection to the article "The case of a missing mobile phone (https://www.experts-exchange.com/articles/28474/The-Case-of-a-Missing-Mobile-Phone.html)". It will help one to understand clearly the steps to track a lost android phone.

#### 737 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

#### Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!