Ujjwal Singh
Ujjwal Singh

Reputation: 4988

Join first n elements of an m sized array

given: $array = ("a0", "a1", "b0", "b1")

How do I join only array[0] & array[1]; Such that:

$a = "a0a1"
# as if: >$a = $a[0]$a[1]

Simillarly,
get: $b = "b0b1"

Upvotes: 2

Views: 2035

Answers (3)

mjolinor
mjolinor

Reputation: 68243

Alternate solution:

$array= ("a1", "a0", "b0", "b1")
$a,$b = &{$ofs='';[string[]]($array[0,1],$array[2,3])}

Upvotes: 2

Rynant
Rynant

Reputation: 24283

You can select the elements in the array, then use the -join operator:

$array = ("a0", "a1", "b0", "b1")
$a = $array[0..1] -join ''
$b = $array[2..3] -join ''

You can use commas to select non-contiguous elements.

$array = ("a0", "a1", "b0", "b1")
$c = $array[0,1,3] -join ''

If there is some criteria for the elements you want joined, you could group the array then join the groups.

# Joins all elements that start with the same character.
$array = ("a0", "a1", "b0", "b1")
$a = $array| group {$_[0]}| foreach {$_.group -join ''}

Upvotes: 5

Dave Sexton
Dave Sexton

Reputation: 11188

Not tested but I think it should work:

$array | % {
 switch -Regex ($_)
  {
    ('a\d') {$a = "$($a)$($_)"}
    ('b\d') {$b = "$($b)$($_)"}
  }

}

Upvotes: 0

Related Questions