I need to find out if 2 arrays match (have common elements) in one or more elements.
Is there a more elegant way than the 2 loops?
In Java I would use a stream with lambda.
lst1.stream ().anyMatch (c -> lst2.contains (c))
But I am not sure hot to do that in Typescript/Javascript.
let lst1 : string [] = ["aaa", "bbb", "ccc"];
let lst2 : string [] = ["ddd", "eee", "bbb"]; // 1 match at "bbb"
let matches : boolean = false;
for (let a of this.lst1)
{
for (let b of this.lst2)
{
if (a == b)
{
matches = true;
}
}
}
3
Answers
would return array of overlaps
How about the some function combined with the includes function?
For example:
Javascript has built-in array functions which can help abstract tasks like this. Particularly
Array.prototype.filter
should be of use in your case.The question has been asked before however, so consider taking a look at this answer (or other answers on this question): https://stackoverflow.com/a/16227294/14775245