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

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

    It can be done by simply iterating across the main array and check whether other array contains any of the target element or not.

    Try this:

    function Check(A) {
        var myarr = ["apple", "banana", "orange"];
        var i, j;
        var totalmatches = 0;
        for (i = 0; i < myarr.length; i++) {
            for (j = 0; j < A.length; ++j) {
                if (myarr[i] == A[j]) {
    
                    totalmatches++;
    
                }
    
            }
        }
        if (totalmatches > 0) {
            return true;
        } else {
            return false;
        }
    }
    var fruits1 = new Array("apple", "grape");
    alert(Check(fruits1));
    
    var fruits2 = new Array("apple", "banana", "pineapple");
    alert(Check(fruits2));
    
    var fruits3 = new Array("grape", "pineapple");
    alert(Check(fruits3));
    

    DEMO at JSFIDDLE

提交回复
热议问题