How to check whether multiple values exist within an Javascript array

前端 未结 10 1950
生来不讨喜
生来不讨喜 2020-11-28 04:32

So, I\'m using Jquery and have two arrays both with multiple values and I want to check whether all the values in the first array exist in the second.

相关标签:
10条回答
  • 2020-11-28 05:22

    Native JavaScript solution

    var success = array_a.every(function(val) {
        return array_b.indexOf(val) !== -1;
    });
    

    You'll need compatibility patches for every and indexOf if you're supporting older browsers, including IE8.

    • Compatibility patch from MDN for .every().
    • Compatibility patch from MDN for .indexOf().

    Full jQuery solution

    var success = $.grep(array_a, function(v,i) {
        return $.inArray(v, array_b) !== -1;
    }).length === array_a.length;
    

    Uses $.grep with $.inArray.


    ES2015 Solution

    The native solution above can be shortened using ES2015's arrow function syntax and its .includes() method:

    let success = array_a.every((val) => array_b.includes(val))
    
    0 讨论(0)
  • 2020-11-28 05:27
    function containsAll(needles, haystack){ 
      for(var i = 0; i < needles.length; i++){
         if($.inArray(needles[i], haystack) == -1) return false;
      }
      return true;
    }
    
    containsAll([34, 78, 89], [78, 67, 34, 99, 56, 89]); // true
    containsAll([34, 78, 89], [78, 67, 99, 56, 89]); // false
    containsAll([34, 78, 89], [78, 89]); // false
    
    0 讨论(0)
  • 2020-11-28 05:27

    Try this.

    var arr1 = [34, 78, 89];
    var arr2 = [78, 67, 34, 99, 56, 89];
    
    var containsVal = true;
    $.each(arr1, function(i, val){
       if(!$.inArray(val, arr2) != -1){
           retVal = false;
           return false;
       }
    });
    
    if(containsVal){
        //arr2 contains all the values from arr1 
    }
    
    0 讨论(0)
  • 2020-11-28 05:29

    I noticed that the question is about solving this with jQuery, but if anyone else who is not limited to jQuery comes around then there is a simple solution using underscore js.

    Using underscore js you can do:

    _.intersection(ArrayA, ArrayB).length === ArrayA.length;
    

    From the docs:

    intersection_.intersection(*arrays) Computes the list of values that are the intersection of all the arrays. Each value in the result is present in each of the arrays.

    _.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]); => [1, 2]

    Ergo, if one of the items in ArrayA was missing in ArrayB, then the intersection would be shorter than ArrayA.

    0 讨论(0)
提交回复
热议问题