I have two arrays and want to match them partially( i.e. some elements of the first array should be present in the second array but not all). I have a solution but I feel I could use a more efficient one. Here is the use case:
const array_1 = [ 7, 6 ];
const array_2 = [ 4, 6 ,7, 2, 9 ];
const isSomeItemMatched = array_1.some( item => array_2.includes(item) );
const isAllItemMatched = array_1.every( item => array_2.includes(item) );
const isPartiallyMatched = !isAllItemMatched && isSomeItemMatched;
Please let me know if there is an optimized way of doing it.
CodePudding user response:
Your solution is fine for small arrays. If they get larger, you'll benefit from turning one into a set:
const array_1 = [ 7, 6 ];
const array_2 = [ 4, 6 ,7, 2, 9 ];
function isPartialMatch(a, b) {
const setA = new Set(a);
return b.some(x => setA.has(x)) && b.some(x => !setA.has(x));
}
console.log(isPartialMatch(array_1, array_2));