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

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

本文关键字:数组 元素 是否 另一个 方法 Lodash 一个 检查      更新时间:2023-09-26

我有两个字符串数组。我要确保第二个数组的所有元素都在第一个数组中。对于这样的事情,我使用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');
}

小提琴在这里。但它相当冗长。是否有内置的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>