简体   繁体   中英

Filtering an array based on a second array?

I have two data arrays:

$arrnames=('a','b','c')
$arrtypes=('x','y','z')

and I have a lookup array:

$arrlookup=('y','z')

I need to return the elements in $arrnames where the matching element in $arrtypes is contained in $arrlookup . I've been playing with foreach looping over $arrnames and looking at the same element in $arrtypes by index but it's getting sloppy and I know there has to be a better way.

I've seen some similar questions, but not anything that strikes me as specifically answering this problem. Being a Powershell very newbie I'm still learning how to adapt examples to my needs. Any help is greatly appreciated.

My code (technique used as applied to above example - actual code is using complex arrays derived from an XML file and has a lot of debugging code so copy/paste is impractical)

foreach ($a in $arrnames) {
    $t=$arrtypes[$arrnames.IndexOf($a)]
    if ($arrlookup.Contains($t)) {
       $arrresult+=$a
    }
)

$arrresult should contain the members of $arrnames that have a type (from $arrtypes) that is in $arrlookup.

Is there a way to use object methods, filtering and the pipeline to simply extract the elements without a foreach loop

Edit - here's the actual code that creates the actual arrays - $builds is an XML document:

$names=$builds.builds.project.name
$types=$builds.builds.project.type

The lookup table is known:

$FXCopTypes=@('batch','component','web')

The XML file I also have control over, but I don't see any way to simplify it more than implementing the hash table code but with the above arrays.

I think you need to change you input inorder to be able to do anything different here. What you are asking for is $arrnames and $arrtypes to really be a hashtable. That way you can access the values using keys.

As it stands I would do this to create the hashtable. The second loop shows how to return each matching value.

$hash = @{} 

for($index = 0; $index -lt $arrtypes.Count; $index++){
    $hash.($arrtypes[$index]) =  $arrnames[$index]      
}

$arrresult = $arrlookup | ForEach-Object{
    $hash[$_]
}

This would return

b
c

If you could get your input to create that hash table then it reduces the need to rebuild it. Also if you know the lookup before hand as well you can filter it then and just have the output you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM