Aviale
Aviale

Reputation: 127

Check if an array contains 2 or more elements of another array in JavaScript

I found a similar answer to my question here: Check if an array contains any element of another array in JavaScript, unfortunately, the OP is asking if ANY elements equal to ANY elements in another array.

In my case, I actually need to check if two or more elements equal to 2 or more elements in another array. Otherwise, it should return false.

I tried methods similar to the mentioned question but I can't get it to target X number of matches...

Array.filter(el => el.colors.some(x => colors2.includes(x)))

This is good only for ANY number of matches...

Upvotes: 2

Views: 2754

Answers (2)

Mystic Groot
Mystic Groot

Reputation: 143

I have something working like this below if this is any useful. Took example form MDN and modified a little bit.

I would go with the @Nguyễn Văn Phong answer. Also, I would use underscore library or similar if you wanted to keep your code tidy. It is just my personal preference :)

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 
'present'];

 const result = words.filter(word => word.length > 6 );

 const result1 = result.includes('exuberant');

 console.log(result);
 // expected output: Array ["exuberant", "destruction", "present"]

 console.log(result1);
 // expected output: true

Upvotes: 1

Nguyễn Văn Phong
Nguyễn Văn Phong

Reputation: 14228

Firstly, you can use array#filter combined with array#includes to find all items in arr1 in arr2.

Then check the length of result.

let arr1 = [1, 2, 3];
let arr2 = [2, 3];

let result = arr1.filter(v1 => arr2.includes(v1));
console.log(result.length >= 2);

Upvotes: 4

Related Questions