Search code examples
arrayspowershellduplicates

PowerShell - Create an array that ignores duplicate values


Curious if there a construct in PowerShell that does this?

I know you can do this:

$arr = @(1,1,1,1,2,2,2,2,3,3,3,3,3,4,4,4,4,4)
$arr = $arr | Get-Unique

But seems like performance-wise it would be better to ignore the value as you are entering it into the array instead of filtering out after the fact.


Solution

  • If are you inserting a large number of items in to an array (thousands) the performance does drop, because the array needs to be reinitialized every time you add to it so it may be better in your case, performance wise, to use something else.

    Dictionary, or HashTable could be a way. Your single dimensional unique array could be retrieved with $hash.Keys For example:

    $hash = ${}
    $hash.Set_Item(1,1)
    $hash.Set_Item(2,1)
    $hash.Set_Item(1,1)
    $hash.Keys
    1
    2
    

    If you use Set_Item, the key will be created or updated but never duplicated. Put anything else for the value if you're not using it, But maybe you'll have a need for a value with your problem too.