Determining whether one array contains the contents of another array in JavaScript/CoffeeScript

后端 未结 5 710
孤独总比滥情好
孤独总比滥情好 2020-12-02 18:20

In JavaScript, how do I test that one array has the elements of another array?

arr1 = [1, 2, 3, 4, 5]
[8, 1, 10, 2, 3, 4, 5, 9].function_name(arr1) # => t         


        
相关标签:
5条回答
  • 2020-12-02 18:43

    You can use array.indexOf():

    pseudocode:

    function arrayContainsAnotherArray(needle, haystack){
      for(var i = 0; i < needle.length; i++){
        if(haystack.indexOf(needle[i]) === -1)
           return false;
      }
      return true;
    }
    
    0 讨论(0)
  • 2020-12-02 18:50
    function arr(arr1,arr2)
    {
        for(var i=0;i<arr1.length;i++)
         {
            if($.inArray(arr1[i],arr2) ==-1)
                   //here it returns that arr1 value does not contain the arr2
            else
                 // here it returns that arr1 value contains in arr2
    
         }
    
    }
    
    0 讨论(0)
  • 2020-12-02 18:57

    I faced the same case if I got you exactly, my case was to check visited places while one trip, every trip have its own point and we have a data for all working area places, here is the code maybe help you.

    https://stackblitz.com/edit/trips-calculator?file=index.js

    0 讨论(0)
  • 2020-12-02 19:00

    No set function does this, but you can simply do an ad-hoc array intersection and check the length.

    [8, 1, 10, 2, 3, 4, 5, 9].filter(function (elem) {
        return arr1.indexOf(elem) > -1;
    }).length == arr1.length
    

    A more efficient way to do this would be to use .every which will short circuit in falsy cases.

    arr1.every(elem => arr2.indexOf(elem) > -1);
    
    0 讨论(0)
  • 2020-12-02 19:09

    ES6 solution using includes:

    [1].every(elem => [1,2,3].includes(elem));
    

    Very similar to Explosion Pills's solution above, just a bit more readable (and arguably a tiny, tiny bit slower).

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