Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell: Combine single arrays into columns

Tags:

powershell

Given:

$column1 = @(1,2,3)
$column2 = @(4,5,6)

How can I combine them into an object $matrix which gets displayed as a matrix with the single arrays as columns:

column1 column2
------- -------
   1       4
   2       5
   3       6
like image 333
Nestor Avatar asked Oct 18 '25 14:10

Nestor


1 Answers

It seems that all of my solutions today requires calculated properties. Try:

$column1 = @(1,2,3)
$column2 = @(4,5,6)

0..($column1.Length-1) | Select-Object @{n="Id";e={$_}}, @{n="Column1";e={$column1[$_]}}, @{n="Column2";e={$column2[$_]}}

Id Column1 Column2
-- ------- -------
 0       1       4
 1       2       5
 2       3       6

If the lengths of the arrays are not equal, you could use:

$column1 = @(1,2,3)
$column2 = @(4,5,6,1)

$max = ($column1, $column2 | Measure-Object -Maximum -Property Count).Maximum    

0..$max | Select-Object @{n="Column1";e={$column1[$_]}}, @{n="Column2";e={$column2[$_]}}

I wasn't sure if you needed the Id, so I included it in the first sample to show how to include it.

like image 164
Frode F. Avatar answered Oct 21 '25 04:10

Frode F.