Combine Individual Items From Separate Arrays Into a Third Array

This topic contains 2 replies, has 2 voices, and was last updated by  awf1130 . 2 years, 10 months ago.

  • Author
  • #29689

    awf1130 .

    I have two arrays, one with a list of first names and a second with a list of last names. What I would like to do is combine the first name and the last name that reside at the same index position in their respective arrays into a third array. Each pair of arrays will always have the same number of items, but that number may change – i.e., in some instances there may be 5 first names and 5 last names, but at other times there may be 15 first names and 15 last names.

    So, for example:

    Array $firstName contains:
    $firstName[0] = Jon
    $firstName[1] = Bob
    $firstName[2] = Tom

    Array $lastName contains:
    $lastName[0] = Smith
    $lastName[1] = Jones
    $lastName[2] = White

    And I want to create array $fullName like this...
    $fullName[0] = Jon Smith
    $fullName[1] = Bob Jones
    $fullName[2] = Tom White

    Thanks for the help.

  • #29690

    Curtis Smith
    PS C:\> $firstName = @("Jon","Bob","Tom")
    PS C:\> $lastName = @("Smith","Jones","White")
    PS C:\> 0..($firstName.Count - 1) | ForEach-Object {$fullName += @("$($firstName[$_]) $($lastName[$_])")}
    PS C:\> $fullName
    Jon Smith
    Bob Jones
    Tom White
  • #29692

    awf1130 .

    Works great! Thanks for the help Curtis!

You must be logged in to reply to this topic.