Home > Software design >  How to map an array of strings into a new array of strings? [duplicate]
How to map an array of strings into a new array of strings? [duplicate]

Time:09-30

I'm trying to write some PowerShell code that takes an array of suffixes and builds a new array with an inputted string prefixed to those suffixes.

How can I do something like C#'s Map or aggregation code to build a new list based off the original list?

In the below powershell ...

$workspaceName = "test"
$deleteableItemSuffixes = @("-api","-asp","-appi")
$deleteableItemNames = ???

I want the resulting array to be ["test-api", "test-asp", "test-appi"], for example.

CodePudding user response:

The -replace operator allows for a concise and efficient solution for string arrays:

# Returns array @('test-api', 'test-asp', 'test-appi')
"-api", "-asp", "-appi" -replace '^', 'test'
  • -replace is regex-based and accepts arrays as input, in which case the operation is performed on each element.

  • ^ matches the position at the beginning of the string, at which the substitution string, 'test' is inserted, in effect prepending that string to each array element (by contrast, $ matches the end of each string and can be used to append a value).


For other data types and if you need more flexibility, you can use the .ForEach() array method (which, in the case of a collection that is already in memory, is faster than the ForEach-Object cmdlet):

("-api", "-asp", "-appi").ForEach({ 'test'   $_ })
  • Strictly speaking, what .ForEach() returns isn't a .NET array, but a collection of type [System.Collections.ObjectModel.Collection[psobject]], but the difference usually doesn't matter in PowerShell.

  • If you do need an actual array, you can simply cast the result:

    # Use the appropriate data type, or simply [array] for an [object[]] array.
    [string[]] ("-api", "-asp", "-appi").ForEach({ 'test'   $_ })
    
  • Related