Lodash 方法检查一个数组中的所有元素是否在另一个数组中

Lodash method to check whether all elements in an array are in another array

我有 2 个字符串数组。我想确保第二个数组的所有元素都在第一个中。我使用 Lodash/Underscore 来处理这样的事情。检查一个字符串是否在数组中时很容易:

var arr1 = ['a', 'b', 'c', 'd'];
_.includes(arr1, 'b');
// => true

但是当它是一个数组时,我看不到当前的方法。我所做的是:

var arr1 = ['a', 'b', 'c', 'd'];
var arr2 = ['a', 'b', 'x'];

var intersection = _.intersection(arr1, arr2);

console.log('intersection is ', intersection);

if (intersection.length < arr2.length) {
    console.log('no');
} else {
    console.log('yes');
}

Fiddle 是 here。但它相当啰嗦。是否有内置的 Lodash 方法?

你可以用_.xor做一个对称的差分,并以长度为准。如果length === 0,两个数组包含相同的元素。

var arr1 = ['a', 'b', 'c', 'd'],
    arr2 = ['a', 'b', 'x'];

console.log(_.xor(arr2, arr1));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>