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

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

    Personally, I would use the following function:

    var arrayContains = function(array, toMatch) {
        var arrayAsString = array.toString();
        return (arrayAsString.indexOf(','+toMatch+',') >-1);
    }
    

    The "toString()" method will always use commas to separate the values. Will only really work with primitive types.

提交回复
热议问题