亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

javascript中數組交集的最簡單代碼

javascript中數組交集的最簡單代碼

javascript中數組交集的最簡單代碼在javascript中實現數組交叉的最簡單,無庫的代碼是什么?我想寫intersection([1,2,3], [2,3,4,5])得到[2, 3]
查看完整描述

3 回答

?
收到一只叮咚

TA貢獻1821條經驗 獲得超5個贊

使用的組合Array.prototype.filterArray.prototype.indexOf

array1.filter(value => -1 !== array2.indexOf(value))

或者正如vrugtehagel在評論中所建議的那樣,你可以使用更新的更Array.prototype.includes簡單的代碼:

array1.filter(value => array2.includes(value))

對于舊瀏覽器:

array1.filter(function(n) {
    return array2.indexOf(n) !== -1;});


查看完整回答
反對 回復 2019-05-27
?
慕蓋茨4494581

TA貢獻1850條經驗 獲得超11個贊

破壞性似乎最簡單,特別是如果我們可以假設輸入已排序:

/* 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;}

非破壞性必須是一個更復雜的頭發,因為我們必須跟蹤索引:

/* 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;}


查看完整回答
反對 回復 2019-05-27
?
翻過高山走不出你

TA貢獻1875條經驗 獲得超3個贊

如果您的環境支持ECMAScript 6 Set,那么一種簡單且有效的(參見規范鏈接)方式:

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

更短,但可讀性更低(也沒有創建額外的交集Set):

function intersect(a, b) {
      return [...new Set(a)].filter(x => new Set(b).has(x));}

避免新Setb每次:

function intersect(a, b) {
      var setB = new Set(b);
      return [...new Set(a)].filter(x => setB.has(x));}

請注意,使用集合時,您將只獲得不同的值,因此new Set[1,2,3,3].size計算結果為3


查看完整回答
反對 回復 2019-05-27
  • 3 回答
  • 0 關注
  • 776 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號