[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 253
  • Last Modified:

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
Asked:
mock5c
2 Solutions
 
ps15Commented:

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

$i = 0;
@sorted = sort map {$_->[$i]} @ary;
0
 
tone28Commented:
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
 
mock5cAuthor 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

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now