skip to Main Content

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


  1. lst1.filter(x => lst2.includes(x))
    

    would return array of overlaps

    Login or Signup to reply.
  2. How about the some function combined with the includes function?

    For example:

    const matches = this.lst1.some(x => this.lst2.includes(x))
    
    Login or Signup to reply.
  3. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search