get sorted column for 2D array

Posted on 2006-05-16
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 = (

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

I just want column i sorted and returned.
Question by:mock5c
    LVL 4

    Accepted Solution


    @ary = (

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

    Assisted Solution

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

    @ary = (

    $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}

    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.

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    How to improve team productivity

    Quip adds documents, spreadsheets, and tasklists to your Slack experience
    - Elevate ideas to Quip docs
    - Share Quip docs in Slack
    - Get notified of changes to your docs
    - Available on iOS/Android/Desktop/Web
    - Online/Offline

    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 (…
    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 (". 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.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    18 Experts available now in Live!

    Get 1:1 Help Now