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

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

    Adding to Array Prototype

    Disclaimer: Many would strongly advise against this. The only time it'd really be a problem was if a library added a prototype function with the same name (that behaved differently) or something like that.

    Code:

    Array.prototype.containsAny = function(arr) {
        return this.some(
            (v) => (arr.indexOf(v) >= 0)
        )
    }
    

    Without using big arrow functions:

    Array.prototype.containsAny = function(arr) {
        return this.some(function (v) {
            return arr.indexOf(v) >= 0
        })
    }
    

    Usage

    var a = ["a","b"]
    
    console.log(a.containsAny(["b","z"]))    // Outputs true
    
    console.log(a.containsAny(["z"]))    // Outputs false
    

提交回复
热议问题