largeQ
2019-05-27 14:24:42
javascript中數(shù)組交集的最簡(jiǎn)單代碼在javascript中實(shí)現(xiàn)數(shù)組交叉的最簡(jiǎn)單,無(wú)庫(kù)的代碼是什么?我想寫intersection([1,2,3], [2,3,4,5])得到[2, 3]
3 回答

收到一只叮咚
TA貢獻(xiàn)1821條經(jīng)驗(yàn) 獲得超5個(gè)贊
使用的組合Array.prototype.filter
和Array.prototype.indexOf
:
array1.filter(value => -1 !== array2.indexOf(value))
或者正如vrugtehagel在評(píng)論中所建議的那樣,你可以使用更新的更Array.prototype.includes
簡(jiǎn)單的代碼:
array1.filter(value => array2.includes(value))
對(duì)于舊瀏覽器:
array1.filter(function(n) { return array2.indexOf(n) !== -1;});

慕蓋茨4494581
TA貢獻(xiàn)1850條經(jīng)驗(yàn) 獲得超11個(gè)贊
破壞性似乎最簡(jiǎn)單,特別是如果我們可以假設(shè)輸入已排序:
/* destructively finds the intersection of * two arrays in a simple fashion. * * PARAMS * a - first array, must already be sorted * b - second array, must already be sorted * * NOTES * State of input arrays is undefined when * the function returns. They should be * (prolly) be dumped. * * Should have O(n) operations, where n is * n = MIN(a.length, b.length) */function intersection_destructive(a, b){ var result = []; while( a.length > 0 && b.length > 0 ) { if (a[0] < b[0] ){ a.shift(); } else if (a[0] > b[0] ){ b.shift(); } else /* they're equal */ { result.push(a.shift()); b.shift(); } } return result;}
非破壞性必須是一個(gè)更復(fù)雜的頭發(fā),因?yàn)槲覀儽仨毟櫵饕?/p>
/* finds the intersection of * two arrays in a simple fashion. * * PARAMS * a - first array, must already be sorted * b - second array, must already be sorted * * NOTES * * Should have O(n) operations, where n is * n = MIN(a.length(), b.length()) */function intersect_safe(a, b){ var ai=0, bi=0; var result = []; while( ai < a.length && bi < b.length ) { if (a[ai] < b[bi] ){ ai++; } else if (a[ai] > b[bi] ){ bi++; } else /* they're equal */ { result.push(a[ai]); ai++; bi++; } } return result;}

翻過高山走不出你
TA貢獻(xiàn)1875條經(jīng)驗(yàn) 獲得超3個(gè)贊
如果您的環(huán)境支持ECMAScript 6 Set,那么一種簡(jiǎn)單且有效的(參見規(guī)范鏈接)方式:
function intersect(a, b) { var setA = new Set(a); var setB = new Set(b); var intersection = new Set([...setA].filter(x => setB.has(x))); return Array.from(intersection);}
更短,但可讀性更低(也沒有創(chuàng)建額外的交集Set
):
function intersect(a, b) { return [...new Set(a)].filter(x => new Set(b).has(x));}
避免新Set
的b
每次:
function intersect(a, b) { var setB = new Set(b); return [...new Set(a)].filter(x => setB.has(x));}
請(qǐng)注意,使用集合時(shí),您將只獲得不同的值,因此new Set[1,2,3,3].size
計(jì)算結(jié)果為3
。
添加回答
舉報(bào)
0/150
提交
取消