0

I have an array of hashtables and I need to find if there are elements who has the same Name.

I have this HasDuplicate function which return True or False if the array contains duplicate or not.

What I am doing here is that I am iterating through each element and add Name of it to another array, and then check it if it exists. But this code does not looks good, and I was thinking if there is another way of achieving this

# object looks like this
$array = @(
    @{ Name = 'First', Passed = $True }
    @{ Name = 'First', Passed = $False }
)

Function HasDuplicate
{
    param($array)
    $all = @()
    foreach($item in $array)
    {
        $item_name = $item.Name
        if($all -contains $item_name)
        {
            Write-Error "Duplicate name ""$item_name"""
            return $True
        }
        else
        {
            $all += $item_name
        }
    }
    return $False
}
1
  • Please define "good looking" Commented Oct 9, 2019 at 13:48

3 Answers 3

8

Group-Object is probably the easiet, something like this:

$array = @(
    @{ Name = 'First'; Passed = $True }
    @{ Name = 'First'; Passed = $False }
)

$array.Name | Group-Object | Where-Object Count -GT 1
Sign up to request clarification or add additional context in comments.

1 Comment

I think you mean -GT 1
0

Another way you could do it using an hash table:

$array = @(
    @{ Name = 'First'; Passed = $True }
    @{ Name = 'First'; Passed = $False }
)


$h = @{}
$array | % {$h[$_.Name] += 1 }
$h.GetEnumerator() | Where value -GT 1

Comments

0

This might not be very good looking compared to the other answers, but you could just count your names in another hashtable then output the duplicates afterwards.

$array = @(
    @{ Name = 'First'; Passed = $True }
    @{ Name = 'First'; Passed = $False }
);

# Count names in array
$counts = @{}
foreach ($object in $array) {
    $name = $object.Name
    if (-not $counts.ContainsKey($name)) {
        $counts[$name] = 0
    }
    $counts[$name] += 1
}

# Output duplicates
foreach ($name in $counts.Keys) {
    if ($counts[$name] -gt 1) {
        Write-Output ("Duplicate Name: " + $name)
    }
}

Output:

Duplicate Name: First

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.