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

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

    What about using a combination of some/findIndex and indexOf?

    So something like this:

    var array1 = ["apple","banana","orange"];
    var array2 = ["grape", "pineapple"];
    
    var found = array1.some(function(v) { return array2.indexOf(v) != -1; });
    

    To make it more readable you could add this functionality to the Array object itself.

    Array.prototype.indexOfAny = function (array) {
        return this.findIndex(function(v) { return array.indexOf(v) != -1; });
    }
    
    Array.prototype.containsAny = function (array) {
        return this.indexOfAny(array) != -1;
    }
    

    Note: If you'd want to do something with a predicate you could replace the inner indexOf with another findIndex and a predicate

提交回复
热议问题