Search code examples
javascripttypescript

Typescript: matches 2 arrays


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;
        }
    }
}

Solution

  • How about the some function combined with the includes function?

    For example:

    const matches = this.lst1.some(x => this.lst2.includes(x))