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

后端 未结 26 1506
礼貌的吻别
礼貌的吻别 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 08:56

    I found this short and sweet syntax to match all or some elements between two arrays. For example

    // OR operation. find if any of array2 elements exists in array1. This will return as soon as there is a first match as some method breaks when function returns TRUE

    let array1 = ['a', 'b', 'c', 'd', 'e'], array2 = ['a', 'b'];
    
    console.log(array2.some(ele => array1.includes(ele)));
    

    // prints TRUE

    // AND operation. find if all of array2 elements exists in array1. This will return as soon as there is a no first match as some method breaks when function returns TRUE

    let array1 = ['a', 'b', 'c', 'd', 'e'], array2 = ['a', 'x'];
    
    console.log(!array2.some(ele => !array1.includes(ele)));
    

    // prints FALSE

    Hope that helps someone in future!

提交回复
热议问题