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

后端 未结 5 739
孤独总比滥情好
孤独总比滥情好 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;
    }
    

提交回复
热议问题