locked
Combine Array Elements RRS feed

  • Question

  • Hi all

    I'm in need of some help.

    Have an array with 4 properties

    Name Type Code Role

    Apple Fruit 01 abc
    Apple Fruit 01 bcd
    Apple Fruit 01 des
    Banana Fruit 02 sha
    Banana Frui 02 zsa

    I need a new array where I can read

    Name Type Code Role

    Apple Fruit 01 abc,bcd,des
    Banana Frui 02 sha,zsa

    all the columns except the last have the same data, I need to combine the last on a one line , separated and remove the remaining lines.

    Can anyone help?

    Thanks


    MCSE Messaging, Productivity & Mobile MCSA Windows 8, 10, 2012 & Office 365 MCTS SCCM 2007 & 2012

    Thursday, October 26, 2017 4:49 AM

Answers

  • Hi,

    the solution is using Group-Object (alias group).

    $groupArr = $arr | group Name
    
    $newArr = @()
    foreach($g in $groupArr)
    {
       $a = "" | select Name,Type,Code,Role
       $firstDataset = $g.group[0]
       $a.Name = $firstDataset.Name
       $a.Typ = $firstDataset.Typ
       $a.Code = $firstDataset.Code
    
       $a.role = ($g.group | select -expandproperty Role) -join ","
       $newArr += $a
    }
    At first, we group your array for name property. Then, for each group a new dataset is created, containing the most information of one element in the group (these properties are the same inside the group). The last property is created by joining all role-properties.


    Thursday, October 26, 2017 5:44 AM

All replies

  • Hi,

    the solution is using Group-Object (alias group).

    $groupArr = $arr | group Name
    
    $newArr = @()
    foreach($g in $groupArr)
    {
       $a = "" | select Name,Type,Code,Role
       $firstDataset = $g.group[0]
       $a.Name = $firstDataset.Name
       $a.Typ = $firstDataset.Typ
       $a.Code = $firstDataset.Code
    
       $a.role = ($g.group | select -expandproperty Role) -join ","
       $newArr += $a
    }
    At first, we group your array for name property. Then, for each group a new dataset is created, containing the most information of one element in the group (these properties are the same inside the group). The last property is created by joining all role-properties.


    Thursday, October 26, 2017 5:44 AM
  • I was trying something similar without re-writing to another array.

    It worked like a charm. 

    Thanks mate.


    MCSE Messaging, Productivity & Mobile MCSA Windows 8, 10, 2012 & Office 365 MCTS SCCM 2007 & 2012

    Thursday, October 26, 2017 6:02 AM