Check if an array contains any element of another array in JavaScript

后端 未结 26 1079
礼貌的吻别
礼貌的吻别 2020-11-22 08:48

I have a target array [\"apple\",\"banana\",\"orange\"], and I want to check if other arrays contain any one of the target array elements.

For example:

26条回答
  •  隐瞒了意图╮
    2020-11-22 09:02

    You can use a nested Array.prototype.some call. This has the benefit that it will bail at the first match instead of other solutions that will run through the full nested loop.

    eg.

    var arr = [1, 2, 3];
    var match = [2, 4];
    
    var hasMatch = arr.some(a => match.some(m => a === m));
    

提交回复
热议问题