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

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

    Array .filter() with a nested call to .find() will return all elements in the first array that are members of the second array. Check the length of the returned array to determine if any of the second array were in the first array.

    getCommonItems(firstArray, secondArray) {
      return firstArray.filter((firstArrayItem) => {
        return secondArray.find((secondArrayItem) => {
          return firstArrayItem === secondArrayItem;
        });
      });
    }
    

提交回复
热议问题