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

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

    My solution applies Array.prototype.some() and Array.prototype.includes() array helpers which do their job pretty efficient as well

    ES6

    const originalFruits = ["apple","banana","orange"];
    
    const fruits1 = ["apple","banana","pineapple"];
    
    const fruits2 = ["grape", "pineapple"];
    
    const commonFruits = (myFruitsArr, otherFruitsArr) => {
      return myFruitsArr.some(fruit => otherFruitsArr.includes(fruit))
    }
    console.log(commonFruits(originalFruits, fruits1)) //returns true;
    console.log(commonFruits(originalFruits, fruits2)) //returns false;

提交回复
热议问题