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

后端 未结 26 1531
礼貌的吻别
礼貌的吻别 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:16

    Vanilla JS

    ES2016:

    const found = arr1.some(r=> arr2.includes(r))
    

    ES6:

    const found = arr1.some(r=> arr2.indexOf(r) >= 0)
    

    How it works

    some(..) checks each element of the array against a test function and returns true if any element of the array passes the test function, otherwise, it returns false. indexOf(..) >= 0 and includes(..) both return true if the given argument is present in the array.

提交回复
热议问题