Main Question :
Ok guys, here is the situation, let's consider 2 string arrays :
string foo = { "Roses are #FF0000" , "Violets are #0000FF", "Paint it #000000"}
string bar = { "Guns", "Roses", "Violets"}
What is the "fewest code lines" way to retrieve strings in foo containing strings in bar ?
(i.e, in this case, the 2 first elements of foo)
Of course I want to avoid doing all the logic "by hand" as I am sure Linq is more efficient with the intersect feature, but I do not know how to use it to perform this precise task.
TieBreakers :
1 - What if foo contains strings that contain more that one element of bar,
string foo = { "Roses are #FF0000" , "Violets are #0000FF", "Paint it #000000"}
string bar = { "Roses", "Violets", "are"}
And I want to avoid duplicates ?
2 - What if I have 2 "bar" arrays that I want to check against one foo array ?
Is it more efficient to merge bar1 and bar2 or to perform the filter with bar1 first and then with bar2 ?
Thanx and have fun answering :-)
Use the inbuilt ES6 function some() to iterate through each and every element of first array and to test the array. Use the inbuilt function includes() with second array to check if element exist in the first array or not. If element exist then return true else return false.
You can use the includes() method in JavaScript to check if an item exists in an array. You can also use it to check if a substring exists within a string. It returns true if the item is found in the array/string and false if the item doesn't exist.
The Arrays. equals() method checks the equality of the two arrays in terms of size, data, and order of elements. This method will accept the two arrays which need to be compared, and it returns the boolean result true if both the arrays are equal and false if the arrays are not equal.
LINQ works well, yes:
var mixed = foo.Where(x => bar.Any(y => x.Contains(y));
Note that you'll still only see each element of foo
once, if at all.
If you have multiple bar
arrays, you can use:
var mixed = foo.Where(x => bar1.Concat(bar2)
.Any(y => x.Contains(y));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With