Mark
Mark

Reputation: 5108

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

I have 2 arrays of string. I want to make sure all elements of the second array are in the first. I use Lodash/Underscore for things like this. Its easy when checking if one astring is in an array:

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

But when its an array, I cant see a current method to do it. What I've done is:

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 is here. But its rather long-winded. Is there a built in Lodash method?

Upvotes: 2

Views: 1551

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386868

You could use _.xor for a symmetric difference and take the length as check. If length === 0, the both arrays contains the same elements.

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>

Upvotes: 2

Related Questions