我有兩個陣列并希望部分匹配它們(即第一個陣列的某些元素應該存在于第二個陣列中,但不是全部)。我有一個解決方案,但我覺得我可以使用更有效的解決方案。這是用例:
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;
請讓我知道是否有優化的方法。
uj5u.com熱心網友回復:
您的解決方案適用于小型陣列。如果它們變大,您將受益于將一個變成一組:
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));
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/497436.html
標籤:javascript 反应 数组 数据结构 前端
上一篇:單擊其他div時關閉Modal
