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

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

    const areCommonElements = (arr1, arr2) => {
        const arr2Set = new Set(arr2);
        return arr1.some(el => arr2Set.has(el));
    };
    

    Or you can even have a better performance if you first find out which of these two arrays is longer and making Set out for the longest array, while applying some method on the shortest one:

    const areCommonElements = (arr1, arr2) => {
        const [shortArr, longArr] = (arr1.length < arr2.length) ? [arr1, arr2] : [arr2, arr1];
        const longArrSet = new Set(longArr);
        return shortArr.some(el => longArrSet.has(el));
    };
    

提交回复
热议问题