2

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...

5
  • 1
    Just check the .length of that result and you'd get the number of matches. Commented May 13, 2021 at 5:11
  • show array and expected result Commented May 13, 2021 at 5:11
  • can yuo show some code? @VLAZ Commented May 13, 2021 at 5:15
  • 1
    @Aviale your code: Array.filter(el => el.colors.some(x => colors2.includes(x))) my code: Array.filter(el => el.colors.some(x => colors2.includes(x))).length Commented May 13, 2021 at 5:15
  • helpful but didn't work. another filter method must be used instead of the some Commented May 13, 2021 at 15:30

2 Answers 2

4

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);

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

Comments

1

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

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.