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

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

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-11-22 09:02

    You can use a nested Array.prototype.some call. This has the benefit that it will bail at the first match instead of other solutions that will run through the full nested loop.

    eg.

    var arr = [1, 2, 3];
    var match = [2, 4];
    
    var hasMatch = arr.some(a => match.some(m => a === m));
    
    0 讨论(0)
  • 2020-11-22 09:02

    Vanilla JS with partial matching & case insensitive

    The problem with some previous approaches is that they require an exact match of every word. But, What if you want to provide results for partial matches?

    function search(arrayToSearch, wordsToSearch) {
        arrayToSearch.filter(v => 
            wordsToSearch.every(w => 
                v.toLowerCase().split(" ").
                    reduce((isIn, h) => isIn || String(h).indexOf(w) >= 0, false)
                )
            )
    }
    //Usage
    var myArray = ["Attach tag", "Attaching tags", "Blah blah blah"];
    var searchText = "Tag attach";
    var searchArr = searchText.toLowerCase().split(" "); //["tag", "attach"]
    
    var matches = search(myArray, searchArr);
    //Will return
    //["Attach tag", "Attaching tags"]
    

    This is useful when you want to provide a search box where users type words and the results can have those words in any order, position and case.

    0 讨论(0)
  • 2020-11-22 09:03

    Update @Paul Grimshaw answer, use includes insteed of indexOf for more readable

    let found = arr1.some(r=> arr2.indexOf(r) >= 0)
    let found = arr1.some(r=> arr2.includes(r))

    0 讨论(0)
  • 2020-11-22 09:04

    Array .filter() with a nested call to .find() will return all elements in the first array that are members of the second array. Check the length of the returned array to determine if any of the second array were in the first array.

    getCommonItems(firstArray, secondArray) {
      return firstArray.filter((firstArrayItem) => {
        return secondArray.find((secondArrayItem) => {
          return firstArrayItem === secondArrayItem;
        });
      });
    }
    
    0 讨论(0)
提交回复
热议问题