Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete items in an array that are in another array

Tags:

powershell

I'm stuck with my script. I need to compare two arrays, one is the result of a query, the other one of a content of a file:

$Array1 = Invoke-Sqlcmd -Query "select name from person"

$Array2 = Get-Content ".\Myfile.txt" #the file is a set of one item
every line

Now, in $Array2 there are items that I would like to delete from the $Array1.

How can I do this? Thank you for yr help!

like image 826
Hari Avatar asked Jul 07 '16 10:07

Hari


People also ask

How do you get the elements of one array which are not present in another array using JavaScript?

Use the . filter() method on the first array and check if the elements of first array are not present in the second array, Include those elements in the output.


2 Answers

Use the Where-Object cmdlet to filter $Array1 based on what is in $Array2:

$Array1 = $Array1 |Where-Object { $Array2 -notcontains $_ }

That works if Invoke-Sqlcmd returns simple strings. If not, you could do something like:

$Array1 = $Array1 |Where-Object { $Array2 -notcontains $_.someProperty }
like image 130
Mathias R. Jessen Avatar answered Nov 15 '22 18:11

Mathias R. Jessen


If performance is an issue, you can get faster results constructing an alternating regex from one of the arrays, and using it as an array operator against the other.

$Array1 = Invoke-Sqlcmd -Query "select name from person"

$Array2 = Get-Content ".\Myfile.txt" #the file is a set of one item
every line

$regex = ‘(?i)^(‘ + (($Array2 |foreach {[regex]::escape($_)}) –join “|”) + ‘)$’

$Array1 -notmatch $regex

Explanation of the code to build the regex here.

like image 30
mjolinor Avatar answered Nov 15 '22 19:11

mjolinor