Gordon
Gordon

Reputation: 6863

Conditionally modify array element without resorting to a temporary array

Given an array like this

$array = @('A', 'B', 'C', 'D', 'E')

I can append something to the end of each item in the array like so

$array = $array | Foreach-Object {"$_ *"}

And if I want to append something DIFFERENT to each member I can do so like this

$tempArray = @()
$count = 1
foreach ($item in $array) {
    $tempArray += "$item $count"
    $count ++
}
$array = $tempArray

But that use of a temporary array seems... clumsy. I feel like I am missing something that would allow conditionally changing the values of the original array instead. Not adding new items, just changing the value of existing items.

Upvotes: 0

Views: 339

Answers (3)

Doug Maurer
Doug Maurer

Reputation: 8868

You don't need to add @(), it's already an array as

$array = 'A', 'B', 'C', 'D', 'E'

If you simply want to append to the string and store back into the array, this is how I would do it. I'm taking advantage of the -Begin, -Process, and -OutVariable parameters of Foreach-Object.

$array | ForEach{$count = 1}{$_ + $count++} -OutVariable array

Output (also stored back in $array)

A1
B2
C3
D4
E5

Now if you did actually want to append a space before the number, then simply add that to the item like this

$array | ForEach{$count = 1}{"$_ " + $count++} -OutVariable array

Output

A 1
B 2
C 3
D 4
E 5

If you need to control the data flow more explicitly I would still lean towards not using for loops. This is equivalent.

$array = 'A', 'B', 'C', 'D', 'E'
$array = 1..$array.Count | ForEach{$array[$_-1] + " $_"}

or you could also write it as

$array = 'A', 'B', 'C', 'D', 'E'
$array = 1..$array.Count | ForEach{"$($array[$_-1]) $_"}

Upvotes: 1

Guenther Schmitz
Guenther Schmitz

Reputation: 1999

you have two options here

1: set the result of the foreach to the variable you are iterating. this will iterate the array and set the result to the same variable.

$count = 1
$array = foreach ($item in $array) {
    "$item $count"
    $count ++
}

2: set an array element like so (note array elements begin by 0 not 1)

$array[2] = 'foo'

or in a loop like like so. this will set each variable at iteration.

$append = 'a'
for($i=0;$i -lt $array.count;$i++){
    $array[$i] = $array[$i],$append -join ' '
    $append += 'a'
}

Upvotes: 1

user7818749
user7818749

Reputation:

Something like this seems to be what you're after:

$array = @('A','B', 'C', 'D', 'E')
for ($c=1; $c -le $array.count; $c++) {
    Write-host "$($array[$c-1]) $c"
}

Upvotes: 0

Related Questions