2

In Powershell I have 3 arrays similar to the below:

Array1:

Date          Value
----          -----
26/06/2021    5
25/05/2021    10
24/06/2021    4


Array2:

Value
-----
9
8
4

Array3:

Value
-----
11
15
20

I want to be able to add the values from Array2 and Array3 as members of Array1 so it finishes up like the below:

Array1:

    Date          Value    Value2    Value3
    ----          -----    ------    ------
    26/06/2021    5        9         11
    25/05/2021    10       8         15
    24/06/2021    4        4         20

For the life of me i can't find out how to do this - all I have managed to do is add the values from Array2 and 3 to the bottom of Array1 but that is not what I'm after.

Is anyone able to help?

JW1990
  • 35
  • 2
  • Can you at least provide the code to set the arrays and produce some valid output. – hmedia1 Jun 25 '21 at 11:15
  • Does this answer your question? [CMD or Powershell command to combine (merge) corresponding lines from two files](https://stackoverflow.com/questions/27233249/cmd-or-powershell-command-to-combine-merge-corresponding-lines-from-two-files). Using this [`Join-Object script`](https://www.powershellgallery.com/packages/Join)/[`Join-Object Module`](https://www.powershellgallery.com/packages/JoinModule) (see also: [Is there a PowerShell equivalent of `paste` (i.e., horizontal file concatenation)?](https://stackoverflow.com/a/68070763/1701026)): `$Array1 |Join $Array2 |Join $Array3` – iRon Jun 25 '21 at 12:53

1 Answers1

4

It's not so much that you'll want to add them to the first array - instead, you'll want to create a new array consisting of new objects that have the property values from all three source arrays.

We can create new objects by casting a hashtable literal to [pscustomobject], so all we need to do is align the items in the arrays.

A simple for loop will do:

for($i = 0; $i -lt $array1.Length; $i++){
  [pscustomobject]@{
    Date   = $array1[$i].Date
    Value  = $array1[$i].Value
    Value2 = $array2[$i].Value
    Value3 = $array3[$i].Value
  }
}
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
  • 1
    +1 on the concise iteration. Something maybe helpful (or not) to add would be that if you wish to refer to say $Array1.Value2 or $Array1.Value3 etc.. then you could set the above into $Array1: `$Array1 = for($i =0 ..... etc...` – hmedia1 Jun 25 '21 at 12:30