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

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

提交回复
热议问题