2

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?

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.